1/3
Looks like no tags are added yet.
Name | Mastery | Learn | Test | Matching | Spaced |
---|
No study sessions yet.
Binary search
A faster algorithm for searching a list if the list's elements are sorted and directly accessible (such as an array).
Binary search first checks the middle element of the list.
If the search key is found, the algorithm returns the matching location.
If the search key is not found, the algorithm repeats the search
1. the remaining left sublist (if the search key was less than the middle element)
2. the remaining right sublist (if the search key was greater than the middle element)
public static int binarySearch(int [] numbers, int key) {
int mid;
int low;
int high;
low = 0;
high = numbers.length - 1;
while (high >= low) {
mid = (high + low) / 2;
if (numbers[mid] < key) {
low = mid + 1;
}
else if (numbers[mid] > key) {
high = mid - 1;
}
else {
return mid;
}
}
return -1; // not found
}
[log2N] + 1
What is the formula for determining the maximum number of steps for a binary search?
binary search for a sorted array (recursion)
public <T> boolean binarySearch(T target, T[] arr, int start, int stop){
int midpoint = (start+stop)/2;
if(start>stop){
return false;
} else if (target.equals(arr[midpoint])){
return true;
} else if (target.compareTo(arr[midpoint] < 0){
return binarySearch(target, arr, start, midpoint-1);
} else {
return binarySearch(target, arr, midpoint+1, stop);
}
}
linear search
Which is faster: sorting and then searching, or just linear search?