Binary search Flashcards

(3 cards)

1
Q

Describe the steps of a binary search.

A
  • Find the midpoint of the list
  • If midpoint is equal to search item, search item is found
  • If search item is greater than the midpoint, search second half of list.
  • This is repeated until the midpoint is equal to the search item.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Write a binary search in pseudocode.

A

array myIntegers[5]
start = 0
end = 4
found = false
input searchItem(“”)
midpoint = 0
while (found == false AND start <= end)
midpoint = (start + end) DIV 2
if (myIntegers[midpoint] == searchItem) then
found = true
elseif (myIntegers[midpoint] > searchItem)
end = midpoint - 1
else
start = midpoint + 1
endif
endwhile

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Compare a linear search and a binary search

A
  • Both work on strings using the ASCII code value
  • Binary search can only be used on sorted data, linear search items do not have to be sorted
  • Linear might be quicker than binary if the search item is at the start of the list
  • If a value is duplicated in the items to be searched, only the first one to be found is returned
How well did you know this?
1
Not at all
2
3
4
5
Perfectly