Created
February 25, 2017 03:10
-
-
Save ShlomiRex/875d4c8168bc567bfda70aab72768c2f to your computer and use it in GitHub Desktop.
Search through sorted list (ascending)
By given number, find the position where the number should go.
Example given array: { 1, 3, 5, 7 }
Number 6 will go after index 2. (after 5 and before 7)
NOTE: Array must be sorted. (Not checking)
NOTE: This is my algorithm. It might not be efficient but I think its doing the job.
Complexity Big-O : O(lg n)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
abstract class MySearch { | |
static int lastPivot = -1; | |
/** | |
* THIS IS MY ALGORITHM it might not be efficient but I didn't use external sources! :D | |
* @param arr <b>MUST BE SORTED ARRAY!</b> | |
* @return Output is POSITION - which the value is less than the position+1. Returns -1 if the number is | |
* minimal from all the values of the array. | |
*/ | |
public static int binarySearch(int[] arr, int number) { | |
int H = arr.length - 1; | |
int L = 0,M; | |
while(true) { | |
M = (L + H) / 2; | |
//if headers L and H are so close, compare both to number. | |
if(H-L == 1) { | |
if(number > arr[H]) | |
return H; | |
else if(number < arr[L]) | |
return L-1; | |
else | |
return L; | |
} | |
//best case senario | |
if(number == arr[M]) | |
return M; | |
if (number < arr[M]) | |
//H = M - 1; | |
H = M; | |
else //number is less than arr[M] | |
//L = M + 1; | |
L = M; | |
} | |
} | |
public static void main(String[] args) { | |
int[] arr = new int[]{5,9,11,20,100,103}; | |
int number = 14; | |
System.out.println("Number " + number + " will go after index " + binarySearch(arr, number)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment