Last active
March 13, 2019 21:00
-
-
Save dkohlsdorf/9e3e955235783a07269c to your computer and use it in GitHub Desktop.
Binary Search
This file contains 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 { | |
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