Last active
January 4, 2020 05:39
-
-
Save jknair0/f668507fc07022eb5897a429781e1abe to your computer and use it in GitHub Desktop.
binary search which returns index of found value.
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
import java.util.Arrays; | |
class BinarySearch { | |
public int search(int[] input, int searchInput) { | |
int n = input.length; | |
if (n == 0) { | |
return -1; | |
} | |
int midPoint = n / 2; | |
int midPointValue = input[midPoint]; | |
if (searchInput == midPointValue) { | |
return midPoint; | |
} | |
if (searchInput < midPointValue) { | |
int[] leftArray = Arrays.copyOfRange(input, 0, midPoint); | |
return search(leftArray, searchInput); | |
} | |
if (searchInput > midPointValue) { | |
int[] rightArray = Arrays.copyOfRange(input, midPoint + 1, n); | |
int rightArrayIndex = search(rightArray, searchInput); | |
return rightArrayIndex == -1 ? rightArrayIndex : midPoint + rightArrayIndex + 1; | |
} | |
return -1; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment