Download presentation
Presentation is loading. Please wait.
1
CSE1301 Computer Programming: Lecture 32 List Sorting
2
Topics Sorting Lists Selection Sort Insertion Sort Reading for this lecture –Goldschlager&Lister, 2.7 –Brookshear p.154
3
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?
4
Selection Sort Basic idea: –find the minimum element –exchange it with the first element of the array –repeat for rest of the array
5
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.
6
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) +.... + 2 + 1 = N(N+1)/2 = O(N 2 )
7
Insertion Sort General idea: –Take the first unsorted item. –Insert it in correct position in sorted part. Insertion Sort Algorithm –See notes
8
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). –1 + 2 +... (N-2) + (N-1) + N = N(N+1)/2 = O(N 2 )
9
Summary Insertion and Selection sort: –worst case both O(N 2 ) Best sorting routines are O(n log(n)) –(in CSE1303 next semester)
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.