Last active
December 10, 2015 06:28
-
-
Save Bekt/4394497 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
| //http://coolcodebro.blogspot.com/2012/12/find-index-in-array-such-that-ai-i.html | |
| void run() { | |
| int[] arr = {-3, -1, 0, 1, 2, 4, 6, 9}; | |
| System.out.printf("Magic index: %d%n", getMagicIndex(arr)); | |
| } | |
| int getMagicIndex(int[] arr) { | |
| if(arr.length == 0) | |
| return -1; | |
| return getMagicIndex(arr, 0, arr.length-1); | |
| } | |
| //Binary search ftw! | |
| int getMagicIndex(int[] arr, int low, int high) { | |
| if(low > high) | |
| return -1; | |
| int mid = (high + low) / 2; | |
| if(arr[mid] < mid) | |
| return getMagicIndex(arr, mid+1, high); | |
| if(arr[mid] > mid) | |
| return getMagicIndex(arr, low, mid-1); | |
| return mid; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment