Download presentation
Presentation is loading. Please wait.
Published byWidya Widjaja Modified over 5 years ago
1
Presents a preliminary view of sorting algorithms
Sample Sorts Presents a preliminary view of sorting algorithms Bubble Sort Selection Sort Serial Sort Bucket Sort 4/16/2019 CS 303 – Sample Sorts Lecture 1
2
Bubble Sort for i = 0 to n-2 // not n-1? No!
for j = n-1 downto i // pay attention to limits! if V[j-1] > V[j] SWAP(j-1,j) // CompareAndSwap Inner loop is executed: (n-1) + (n-2) + (n-3) + … = (n-1)(n/2) = n2/2 – n/2 = O(n2) Prove it! Experiments: [11150,11967] 4/16/2019 CS 303 – Sample Sorts Lecture 1
3
Selection Sort for i = 0 to n-2 // for each output slot {
best = i // find the best item for j = i+1 to n-1 if V[best] > V[j] best = j // CompareAndRememberBest?? SWAP(best,i) // put it there } Optimized version of BubbleSort Inner loop finds index of smallest element Fewer SWAPs (exactly n-1), but still O(n2) comparisons Experiments: [7933,8733] 4/16/2019 CS 303 – Sample Sorts Lecture 1
4
Serial Sort i = 0 for k = 0 to m-1 // for each value for j = i to n-1
if k == V[j] SWAP(i++,j) // move to the front Does not use <= O(n*m) m = range of values n = size of input Experiments: [666,784] 4/16/2019 CS 303 – Sample Sorts Lecture 1
5
Bucket Sort for t = 0 to m-1 B[t] = 0 // O(m)
for i = 0 to n-1 B[V[i]] // O(n) i = 0 for t = 0 to m // O(m*n)? no! O(n) for u = 1 to B[t] V[i++] = t Does not use <= Uses extra space Does not carry along entire record O(n+m) Experiments: [50,67] 4/16/2019 CS 303 – Sample Sorts Lecture 1
6
Sample Sort Recap Sorts that use <= Bubble, Selection -- O(n2)
Can we do better? Yes, we can get to O(nlogn) Sorts that “cheat” Serial -- O(m*n) Bucket -- O(m+n) time; O(m) space Experimental results Bubble Selection Serial Bucket $ $8300 $ $60 4/16/2019 CS 303 – Sample Sorts Lecture 1
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.