11/10/2014 12:24 pm Monday Week 11 Page 1 of 5 http://www.cse.unsw.edu.au/~cs1921/14s2/slides/week11a/notes.html
Monday Week 11 Sorting Algorithms
1/15
We will discuss three sorting algorithms Selection Sort Insertion Sort Quick Sort
Selection Sort
2/15
This is the sorting method we saw last week. Basic algorithm (based on arrays): Starting with the first element in a list if this is the last element in the list, you have finished find the minimum in the list, and swap with the first element redefine the list as starting with the next element do next iteration Example animation
... Selection Sort
3/15 void selSort(int array[], int n) { // an 'in place' sort so ... int i; // ... the array is 'overwritten' int min; int marker; for (marker=0; marker < n; marker++) { min = marker; // assume element 'marker' is min for (i = marker+1; i < n; i++) { if (array[i] < array[min]) { min = i; // found better min at 'i' } } int tmp; tmp = array[marker]; array[marker] = array[min]; // swap elements 'min' ... array[min] = tmp; // ... and 'marker' } }
Exercise: Performance of Selection Sort
4/15
11/10/2014 12:24 pm Monday Week 11 Page 2 of 5 http://www.cse.unsw.edu.au/~cs1921/14s2/slides/week11a/notes.html
Measure performance of selection sort using the UNIX time command 1,000 numbers 10,000 numbers 100,000 numbers
randomly generated already ordered reverse ordered (numbers in descending order)
... Exercise: Performance of Selection Sort
5/15
Selection sort is typical of a class of quadratic algorithms these have quadratic performance quadratic means to the power of 2 execution time is proprtional to the square of the input N
double N, quadruple the time triple N, increase the time by factor 9 increase N by a factor of 10, it takes 102 = 100 times as long to execute increase N by a factor of 100, it takes 1002 = 10000 times as long to execute etc
This is slower than linear algorithms (e.g. random number generation)
Selection Sort on Linked Lists
6/15
Sort algorithms are usually implemented using arrays: allow random access
every element can be accessed immediately
are implemented efficiently/concisley Sort algorithms can beimplemented on other data structures linked lists even stacks (really!?) It depends on the sort algorithm whether this is very inefficient or not
... Selection Sort on Linked Lists
7/15
In Selection Sort
- utside loop: