Announcements: HW1 available, due 9/13, 11:59p. PA1 available, due - - PowerPoint PPT Presentation

β–Ά
announcements
SMART_READER_LITE
LIVE PREVIEW

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> __________


slide-1
SLIDE 1

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

slide-2
SLIDE 2

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):

slide-3
SLIDE 3

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:

slide-4
SLIDE 4

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:

slide-5
SLIDE 5

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:

slide-6
SLIDE 6

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