Announcements: HW1 available, due 9/13, 11:59p. PA1 available, due - - PowerPoint PPT Presentation
Announcements: HW1 available, due 9/13, 11:59p. PA1 available, due - - PowerPoint PPT Presentation
Announcements: HW1 available, due 9/13, 11:59p. PA1 available, due 9/27, 11:59p. Todays plan: Selection Sort Weird function Insertion Sort Recap of linear sorts Selection Sort: (correctness continued) vector<string> __________
Selection Sort: (correctness continued)
vector<string> __________ (vector<string> & candy){ for (int i = 0; i < candy.size(); i++){ int min = findMin(candy,i); swap(candy[i], candy[min]); } return candy;} 1 2 3 4 5 6
4) IH (assume LI holds at start of ith iteration): * πππππ§[0. . π β 1] sorted * π¦ β πππππ§ 0. . π β 1 , π§ β πππππ§[π. . π β 1] β π¦ β€ π§. * πππππ§βs set of elements never changes. 5) Inductive step (show LI holds at start of step i+1): 6) Termination (last value of iterator):
Weird mystery function
void ________ (vector<string> & candy, int loc){ // assumes candy[0:loc-1] is sorted, loc valid string temp = candy[loc]; int j = loc; while (j > 0 && candy[j-1] > temp) { candy[j] = candy[j-1]; j--; } candy[j] = temp; } 1 2 3 4 5 6 7 8 9
Functionality (whatβs a good name)? Running Time? Correctness? 1) variable: 2) invariant:
Insertion Sort
vector<string> insertionSort (vector<string> & candy){ for (int i = 1; i < candy.size(); i++) { ____________(candy, i); return candy; } 1 2 3 4
Functionality? Running Time? Correctness? 1) Iterative variable: 2) Loop invariant:
Insertion Sort
vector<string> insertionSort (vector<string> & candy){ for (int i = 1; i < candy.size(); i++) { ____________(candy, i); return candy; } 1 2 3 4
3) Base case: 4) IH: 5) Inductive step: 6) Termination:
Linear Sorts, recap
We have learned and analyzed selection sort and insertion sort. Which is better?
- Asymptotically?
- Empirically?
- What if list is already sorted?
- What if list is almost sorted?
- What if list is in reverse order?