Download presentation
Presentation is loading. Please wait.
Published byArnold Osborne Modified over 9 years ago
1
Sorting List is rearranged into sorted order How is the sorted order determined? – The ItemType is responsible for determining the key to be used in comparison of instances of the item. – The ItemType relational operator< determines the sorted order of the list. To be really efficient, we also need a fast sort algorithm.
2
Common Sort Algorithms Bubble SortHeap Sort Selection SortMerge Sort Insertion SortQuick Sort There are many known sorting algorithms. Bubble sort is the slowest, running in n 2 time. Quick sort is the fastest, running in n lg n time. As with searching, the faster the sorting algorithm, the more complex it tends to be.
3
Selection Sort Selection sort algorithm: sorts a list by selecting the smallest element in the list and then moving this element to the top of the list The first time we locate the smallest item in the entire list The second time we locate the smallest item in the rest of the list starting, etc.
4
Selection Sort The approach of Selection Sort: – select one value and put it in its final place in the sort list – repeat for all other values In more detail: – find the smallest value in the list – switch it with the value in the first position – find the next smallest value in the list – switch it with the value in the second position – repeat until all values are placed
5
Selection Sort An example: sort the list 61, 39, 32, 21, 2, 37 pass 1:61393221 237 pass 2: 23932216137 pass 3: 22132396137 pass 4: 22132396137 pass 5: 22132376139 result: 22132373961
6
Selection Sort Routine void ListType::SelSort() { ItemType item; int passCount; int searchIndx; int minIndx; for (passCount = 0; passCount < length-1; passCount++) { minIndx = passCount; for (searchIndx = passCount+1; searchIndx<length; searchIndx++) if ( data[searchIndx] < data[minIndx] ) minIndx = searchIndx; item = data[minIndx]; data[minIndx] = data[passCount]; data[passCount] = item; }
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.