Advertisement
ahmed19981973

Untitled

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