ahmed19981973

Untitled

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