Gene wrote: > Terry wrote: > > If i have an array like {1,4, 10, 15 , 20 , 30 } of size n , now if i > > want to search for number > > > > 25 , i should get 20 , if i search for number 11 i hould get 10 , if i > > search for 4 i should get 4, if i search for a number and it doesn't > > exist i should get the lower number between which it lies. All numbers > > are bound to lie between 1 and n. > > > > Can you tell me a easy way to do it. > > If the array is always sorted you can modify a standard binary search > to get job done in O(log n) time. This looks like homework.
Can someone give me a better version / elegant version int search (int low, int high, int num) { int mid = (high + low) / 2; if (num <= arr1[0]) return 0; if (num >= arr1[cnt - 1]) return cnt - 1; if (arr1[mid] == num) return mid; if (arr1[high] == num) return high; if (arr1[low] == num) return low; if (low == high) { if (num == arr1[low]) return low; if (num < arr1[low]) { gflag = 1; return low - 1; } if(num > arr1[low]) { gflag=1; return low; } } if ((high - low) == 1) { gflag = 1; return low; } if (arr1[mid] > num) { high = mid - 1; return search (low, high, num); } if (arr1[mid] < num) { low = mid + 1; return search (low, high, num); } } --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Algorithm Geeks" group. To post to this group, send email to algogeeks@googlegroups.com To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/algogeeks -~----------~----~----~----~------~----~------~--~---