Skip to content

Instantly share code, notes, and snippets.

@dkohlsdorf
Last active March 13, 2019 21:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dkohlsdorf/9e3e955235783a07269c to your computer and use it in GitHub Desktop.
Save dkohlsdorf/9e3e955235783a07269c to your computer and use it in GitHub Desktop.
Binary Search
public class BinarySearch {
public static int search(int[] sorted, int element) {
int min = 0;
int max = sorted.length;
while(max > min) {
int mid = min + (max - min) / 2;
if(sorted[mid] == element) {
return element;
} else if(sorted[mid] < element){
min = mid + 1;
} else {
max = mid - 1;
}
}
return -1;
}
public static void main(String[] args) {
System.out.println(search(new int[]{1,2,3,4,5}, 3));
System.out.println(search(new int[]{1,2,3,4,5}, 12));
System.out.println(search(new int[]{1,2,3,4,5}, 1));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment