16.2 Binary search

0.0(0)
studied byStudied by 2 people
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
Card Sorting

1/3

encourage image

There's no tags or description

Looks like no tags are added yet.

Study Analytics
Name
Mastery
Learn
Test
Matching
Spaced

No study sessions yet.

4 Terms

1
New cards

Binary search

A faster algorithm for searching a list if the list's elements are sorted and directly accessible (such as an array).

  1. Binary search first checks the middle element of the list.

  2. If the search key is found, the algorithm returns the matching location.

  3. 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
}

2
New cards

[log2N] + 1

What is the formula for determining the maximum number of steps for a binary search?

3
New cards

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);
	}
}

4
New cards

linear search

Which is faster: sorting and then searching, or just linear search?