Tut 08 - Searching and Sorting
Problem Set 21
Problem 21.1
The Loop version of Binary Search
Problem 21.2*
Question: Instead of returning -1 if the query q
is not found, modify the binary search algorithm in Problem 21.1 such that it returns either:
a position
k
, such thatlist[k] <= q <= list[k+1]
.-1
ifq < list[0]
n - 1
ifq > list[n-1]
Problem Set 22
Problem 22.1*
Optimize the Bubble Sort.
Basically, when there is not swap, which means our list is sorted already.
Problem 22.2*
Insertion sort by doing:
take the first element X from the unsorted partition
use binary search to find the correct position to insert X
insert X into the right place
In Line 20, curr-1
means we exclude our current number from the search range first. And the +1
at last is because we want to insert at the position behind what we find using Problem 21.2*
Last updated