Download presentation
Presentation is loading. Please wait.
Published byRose Walker Modified over 5 years ago
1
Sorting Problem Definition Silly Sort Bubble Sort Selection Sort
Insertion Sort 4/3/2019 CS 303 – Sorting Lecture 14
2
Sorting Given A sequence of records – V[i]
Key - field to sort on - V[i].key ‘<=‘ - Linear Ordering Relationship (on Keys) Problem Arrange records so that Keys are non-decreasing Generalizations usually best to sort a list of pointers system should provide a facility to define ‘<=‘ we’ll use <, <=, >, >= as needed, i.e., V[i].key > V[i+1].key even better...let’s use Compare(i,j) (and CompareAndSwap(i,j)) 4/3/2019 CS 303 – Sorting Lecture 14
3
Silly Sorts ReallySilly(n) Repeat i rand(1,i); j rand(i+1,n)
CompareAndSwap(i,j) Until Sorted O(???) Silly(n) for i 1 to n /* for each slot */ for j n downto /* find correct x */ CompareAndSwap(j-1,j) O(n2) we can improve this one a bit, to get... 4/3/2019 CS 303 – Sorting Lecture 14
4
Bubble Sort BubbleSort(n) for i 1 to n-1 /* for each slot */
for j n downto i /* find correct x */ CompareAndSwap(j-1,j) O(n2) Notice that all sorts (so far) have used CompareAndSwap, and have not taken note of the result of the Compare. They all do the same comparisons, no matter what the input data. They are “oblivious”. 4/3/2019 CS 303 – Sorting Lecture 14
5
Selection Sort SelectionSort(n) for i 0 to n-2
{ /* i are correct */ Best i for j i+1 to n-1 if Compare(j,Best) Best j Swap(i,Best) } or ExchangeSort(n) for j i+1 to n-1 CompareAndSwap(i,j) Which is better? [depends on architecture!] Which is oblivious? 4/3/2019 CS 303 – Sorting Lecture 14
6
Insertion Sort InsertionSort(n) for i 1 to n-1
{ /* i-1 are sorted (not “correct”) */ j i while CompareAndSwap(j,j-1) j j-1 } Beware! This program does not work! Why not? Demonstrate! Fix by: sentinel (use V[0], if available) add test for j >1 to inner loop (ouch!) add 1 pass of (say) BubbleSort to swap Min with V[1] 4/3/2019 CS 303 – Sorting Lecture 14
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.