CSE1301 Computer Programming: Lecture 32 List Sorting
Topics Sorting Lists Selection Sort Insertion Sort Reading for this lecture –Goldschlager&Lister, 2.7 –Brookshear p.154
Sorting Aim: –Start with unsorted array –End with sorted array How to sort student records? –depends on purpose – by name, ID number, marks Project: How to sort words?
Selection Sort Basic idea: –find the minimum element –exchange it with the first element of the array –repeat for rest of the array
Selection Sort Example Example: see Notes Algorithm and Code: see Notes –Main module selectionSort Need to keep track of position of first unsorted element. –Submodule findIndexMin Find the position of the minimal element in the rest of the array.
Selection Sort Analysis What is the running time of this algorithm? Worst case: each time through? –Have to do linear search on rest of the array. – N + (N-1) + (N-2) = N(N+1)/2 = O(N 2 )
Insertion Sort General idea: –Take the first unsorted item. –Insert it in correct position in sorted part. Insertion Sort Algorithm –See notes
Insertion Sort Analysis What is the running time of this algorithm? Worst case: each time through? –Insert at start of array each time (shift all sorted elements along each time). – (N-2) + (N-1) + N = N(N+1)/2 = O(N 2 )
Summary Insertion and Selection sort: –worst case both O(N 2 ) Best sorting routines are O(n log(n)) –(in CSE1303 next semester)