Binary Search

0.0(0)
studied byStudied by 0 people
GameKnowt Play
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

What is binary search?

This is an algorithm that searches for a target number in an ordered numeric data structure by dividing the search area in half each time. This results in a time complexity of O(log n)

2
New cards

What does O(log n) give a hint to and mean?

It hints that binary search should be used and log n means basically if you have an input size of n, the maximum number of checks needed is log n. So basically if n = 2 then it would be O(1). If n = 4 it would be O(2), because we would have to check 2 sets of 2.

3
New cards

How to do the binary search problem?

class Solution:
    def search(self, nums: List[int], target: int) -> int:
        start_index = 0
        end_index = len(nums) - 1


        while start_index <= end_index:
            middle_index = (start_index + end_index) // 2

            if target == nums[middle_index]:
                return middle_index
            elif target < nums[middle_index]:
                end_index = middle_index - 1
            elif target > nums[middle_index]:
                start_index = middle_index + 1
        return -1    	

4
New cards

What does // do/mean?

It is the floor division operator and means to divide and round down.