A binary search algorithm finds the position of a specified input value (the search "key") within an array sorted by key value. For binary search, the array should be arranged in ascending or descending order. In each step, the algorithm compares the search key value with the key value of the middle element of the array. If the keys match, then a matching element has been found and its index, or position, is returned. Otherwise, if the search key is less than the middle element's key, then the algorithm repeats its action on the sub-array to the left of the middle element or, if the search key is greater, on the sub-array to the right. If the remaining array to be searched is empty, then the key cannot be found in the array and a special "not found" indication is returned.
Source Code
import java.util.Arrays;
public class BinarySearch {
public static void main(String[] args) {
int[] numbers = { 84, 69, 76, 86, 94, 91 };
System.out.println("Before sort: " + Arrays.toString(numbers));
Arrays.sort(numbers);
System.out.println("After sort: " + Arrays.toString(numbers));
BinarySearch binarySearch = new BinarySearch();
System.out.println("84 is in: "
+ binarySearch.binarySearch(numbers, 84));
System.out.println("76 is in: "
+ binarySearch.binarySearch(numbers, 76));
System.out.println("95 is in: "
+ binarySearch.binarySearch(numbers, 95));
}
private int binarySearch(int[] numbers, int search) {
int min = 0;
int max = numbers.length - 1;
while (min <= max) {
int midPoint = min + (max - min) / 2;
if (numbers[midPoint] > search) {
max = midPoint - 1;
} else if (numbers[midPoint] < search) {
min = midPoint + 1;
} else if (numbers[midPoint] == search) {
return midPoint;
}
}
return -1;
}
}
Complexity Analysis
Case | Complexity |
---|---|
Worst case performance | O(log n) |
Best case performance | O(1) |
Average case performance | O(log n) |
No comments:
Post a Comment