Announcements: HW1 available, due 9/13, 11:59p. PA1 available, due 9/27, 11:59p. Todayβs plan: Selection Sort Weird function Insertion Sort Recap of linear sorts
Selection Sort: (correctness continued) vector<string> __________ (vector<string> & candy){ 1 for (int i = 0; i < candy.size(); i++){ 2 int min = findMin(candy,i); 3 swap(candy[i], candy[min]); 4 } 5 return candy;} 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){ 1 // assumes candy[0:loc-1] is sorted, loc valid 2 string temp = candy[loc]; 3 int j = loc; 4 while (j > 0 && candy[j-1] > temp) { 5 candy[j] = candy[j-1]; 6 j--; } 7 candy[j] = temp; 8 } 9 Functionality (whatβs a good name)? Running Time? Correctness? 1) variable: 2) invariant:
Insertion Sort vector<string> insertionSort (vector<string> & candy){ 1 for (int i = 1; i < candy.size(); i++) { 2 ____________(candy, i); 3 return candy; } 4 Functionality? Running Time? Correctness? 1) Iterative variable: 2) Loop invariant:
Insertion Sort vector<string> insertionSort (vector<string> & candy){ 1 for (int i = 1; i < candy.size(); i++) { 2 ____________(candy, i); 3 return candy; } 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? https://www.toptal.com/developers/sorting-algorithms
Recommend
More recommend