fueanta

Find Nearest Smaller

May 29th, 2017
108
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. int closestSmallerSearch(int list[], int size, int value)
  2. {
  3.     int low = 0, high = size - 1;
  4.     int mid = 0;
  5.  
  6.     while (low <= high)
  7.     {
  8.         mid = low + ((high - low) / 2); // (low + high) / 2
  9.  
  10.         if (list[mid] == value)
  11.         {
  12.             return (mid - 1); // if matches then we need the index - 1 here
  13.         }
  14.         else if (list[mid] < value)
  15.         {
  16.             low = mid + 1;
  17.         }
  18.         else
  19.         {
  20.             high = mid - 1;
  21.         }
  22.     }
  23.  
  24.     if (low == high) // if not matches , we need the smaller nearest
  25.     {
  26.         if (list[low] < list[mid])
  27.         {
  28.             return low;
  29.         }
  30.         else if (list[low] > list[mid])
  31.         {
  32.             return (low - 1);
  33.         }
  34.     }
  35. }
RAW Paste Data