ahmed19981973

Untitled

Mar 30th, 2019
460
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.80 KB | None | 0 0
  1.  /**assume the array is [3, 0, 0, 0, 0, 0, 0, 0, 0 , 9].
  2.      * 1-lets assume that previous bottom and previous top are probableBottom and probableTop respectively
  3.      * so that we can keep track where should we back if discovering that we are  in wrong direction.
  4.      * 2-check that we are in the wrong direction or not,how can we check?
  5.      * actually  the array is almost sorted so assume the middle index is 4 that equal 0(arr[4]=0)
  6.      * and key=9 so according to the binary search algorithm it will move to right(9>0)
  7.      * any positive number is more than zero so it will move to right often.
  8.      * so the new  start=4+1 and  end=9 the array is quite sorted so the key should belong to
  9.      * range [start,end] and if the key is less than start then it will not belong this range ([start,end])
  10.      * so it should go back as he is in wrong direction these can be made  if (key<arr[bottom]) then
  11.      *  middle=(probablBottom+probablTop)/2;//go back to previous range .you should store the previous top and bottom in
  12.      *  each once so when test (key>arr[middle]) you should make probablTop=middle-1
  13.      *  and the rest off binary search algorithms is the same
  14.      **/
  15.     public static int search3(Integer key, int [] arr){
  16.         int middle;
  17.         int top=arr.length-1;
  18.         int bottom=0;
  19.         int probablTop=top,probablBottom=bottom;
  20.         while (top >= bottom) {
  21.            middle=(top+bottom)/2;
  22.            if (key<arr[bottom]){
  23.               middle=(probablBottom+probablTop)/2;
  24.            }
  25.            if (arr[middle]==key)
  26.                return middle;
  27.            else if (key>arr[middle]){
  28.                probablTop=middle-1;
  29.                bottom=middle+1;
  30.            }
  31.            else {
  32.                top = middle - 1;
  33.            }
  34.         }
  35.         return -1;
  36.     }
Advertisement
Add Comment
Please, Sign In to add comment