T10_sort - COMP 152 Simple(but Slow Sorting Algorithms 1...

Info iconThis preview shows pages 1–5. Sign up to view the full content.

View Full Document Right Arrow Icon
COMP 152 Simple (but Slow) Sorting Algorithms 1 Tutorial #11 Spring 2010 Simple (but Slow) Sorting Algorithms Selection sort Bubble sort Rank sort Shell sort You may want to go to the course webpage under “many applets” to experiment with diferent sorting al- gorithms
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
COMP 152 Simple (but Slow) Sorting Algorithms 2 Selection Sort Determine the largest element and move it to a[n-1] Then determine the largest of the remaining n 1 elements and move it to a[n-2] , etc. template < class T > void SelectionSort(T a[], int n) { // Sort the n elements a[0:n-1]. for ( int size = n; size > 1; size--) { int j = Max(a, size); Swap(a[j], a[size - 1]); } } What is its complexity for the worst case, and the best case?
Background image of page 2
COMP 152 Simple (but Slow) Sorting Algorithms 3 Tuning Selection Sort for EFciency It continues to work even after the elements have been sorted (sorted list)! Early-termination version: template < class T > void SelectionSort(T a[], int n) { // Early-terminating version of selection sort. bool sorted = false; for ( int size = n; !sorted & (size > 1); size--) { int pos = 0; sorted = true; // find largest for ( int i = 1; i < size; i++) if (a[pos] <= a[i]) pos = i; else sorted = false; // out of order Swap(a[pos], a[size - 1]); } } What is its complexity for the worst case, and the best case?
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
COMP 152 Simple (but Slow) Sorting Algorithms 4 Bubble Sort The largest element is “bubbled” up to the end of the array Get the largest element to the right
Background image of page 4
Image of page 5
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 08/25/2010 for the course COMP COMP152 taught by Professor D.y.yeung during the Spring '10 term at HKUST.

Page1 / 11

T10_sort - COMP 152 Simple(but Slow Sorting Algorithms 1...

This preview shows document pages 1 - 5. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online