Created
September 8, 2019 19:08
-
-
Save sheradmin/3c43d7760d4baaec38e9e9035ffb558b to your computer and use it in GitHub Desktop.
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 BinarySearch { | |
| /** | |
| * Returns index of x if it is present in arr[start.. end] | |
| * @param arr | |
| * @param start | |
| * @param end | |
| * @param x | |
| * @return | |
| */ | |
| private int binarySearch(int[] arr, int start, int end, int x) { | |
| if (start >= end) { | |
| return -1; | |
| } | |
| int mid = (start + end) / 2; | |
| // If the element is present at the | |
| // middle itself | |
| if (arr[mid] == x) { | |
| return mid; | |
| } | |
| if (arr[mid] < x) {//left half part | |
| return binarySearch(arr, mid + 1, end, x); | |
| } else if (arr[mid] > x) {//right half part | |
| return binarySearch(arr, start, mid - 1, x); | |
| } | |
| return -1; | |
| } | |
| private void search(int[] arr, int x) { | |
| int r = binarySearch(arr, 0, arr.length, x); | |
| System.out.println("x = " + x + "; index = " + r); | |
| } | |
| public static void main(String[] args) { | |
| int[] arr = new int[1]; | |
| // int[] arr = new int[10]; | |
| // int[] arr = new int[Integer.MAX_VALUE]; | |
| for (int i = 0; i < arr.length; i++) { | |
| arr[i] = i; | |
| } | |
| System.out.println("length = " + arr.length); | |
| BinarySearch binarySearch = new BinarySearch(); | |
| binarySearch.search(arr, 170); | |
| binarySearch.search(arr, 2); | |
| binarySearch.search(arr, 3); | |
| binarySearch.search(arr, -1); | |
| binarySearch.search(arr, 0); | |
| binarySearch.search(arr, 100); | |
| binarySearch.search(arr, 7); | |
| binarySearch.search(arr, 6); | |
| binarySearch.search(arr, 600765); | |
| binarySearch.search(arr, 1211211212); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment