Skip to content

Instantly share code, notes, and snippets.

@davepkennedy
Created September 17, 2020 21:34
Show Gist options
  • Save davepkennedy/48ad33dc09def65104c3094d28277b11 to your computer and use it in GitHub Desktop.
Save davepkennedy/48ad33dc09def65104c3094d28277b11 to your computer and use it in GitHub Desktop.
static boolean contains (int[] h, int n) {
int low = 0;
int high = h.length;
int d;
do {
d = (high - low) / 2;
int mid = low + d;
if (h[mid] == n) {
return true;
} else if (h[mid] < n) {
low = mid;
} else {
high = mid;
}
} while (d > 0);
return false;
}
@davepkennedy
Copy link
Author

Determine if a needle is in a haystack.
Haystack needs to be sorted beforehand.
Complexity should be O(log n) since we're not searching the whole of the haystack for the needle

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment