Created
April 7, 2019 09:34
-
-
Save beeTechMantra/bb6104f1d1ee24eef03f51ffedc1af1c to your computer and use it in GitHub Desktop.
Binary Search
This file contains hidden or 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
public class MyBinarySearch { | |
public int binarySearch(int[] inputArr, int key) { | |
int start = 0; | |
int end = inputArr.length - 1; | |
while (start <= end) { | |
int mid = (start + end) / 2; | |
if (key == inputArr[mid]) { | |
return mid; | |
} | |
if (key < inputArr[mid]) { | |
end = mid - 1; | |
} else { | |
start = mid + 1; | |
} | |
} | |
return -1; | |
} | |
public static void main(String[] args) { | |
MyBinarySearch mbs = new MyBinarySearch(); | |
int[] arr = {2, 4, 6, 8, 10, 12, 14, 16}; | |
System.out.println("Key 14's position: "+mbs.binarySearch(arr, 14)); | |
int[] arr1 = {6,34,78,123,432,900}; | |
System.out.println("Key 432's position: "+mbs.binarySearch(arr1, 432)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment