Download presentation
Presentation is loading. Please wait.
Published byDuane Sharp Modified over 9 years ago
1
Sorting Sorting Problem: A list of items: x1, x2, x3, …., xn Arranging the list in ascending order X1 <= X2 <= X3 <= … <= Xn Or descending order X1 >= X2 >= X3 >= … >= Xn
2
Some sorting schemes One classification of sorting schemes consists of three categories: Selection sorts Exchange sorts Insertion sorts
3
Selection sort Basic idea: make number of passes through the list or a part of the list and, on each pass, select one element to be correctly positioned. Example: on each pass through a sublist, the smallest element in this sublist might be found and then moved to its proper location
4
Selection sort Original list: Scan the smallest Interchange Continue on sublist 67 33 21 84 49 50 75 21 33 67 84 49 50 75 21 33 49 84 67 50 75 21 33 49 50 67 84 75 21 33 49 50 67 75 84
5
Simple selection sorting algorithm A list is stored in array x[0],…x[n-1] For I = 0 to n-1 do the following // find the smallest in sublist x[i] to x[n-1] Set pos = I Set min = x[pos] For j = i+1 to n-1 do the following If x[j] < min Set pos = j Set min = x[j] // now interchange the smallest and the beginning of sublist Set x[pos] = x[i] Set x[i] = min
6
Exchange sort Selection sort in which some element is selected and them moved to its correct position Exchange sort interchange pairs of elements that are out of order until eventually no such pairs remain and the list is therefore sorted Example: bubble sort
7
Insertion sorts Based on the same idea as the algorithms for inserting new element into ordered linked list 67 33 21 84 49 50 75 67 21 84 49 50 75 33 67 21 84 49 50 75 21 33 67 84 49 50 75 21 33 49 67 84 50 75 21 33 49 50 67 84 75 21 33 49 50 67 75 84
8
algorithm Array x[0], …, x[n-1] For I = 0 to n-1 do following Set temp = x[i] Set j = I While temp < x[j-1] do the following // shift element to the right to open spot X[j] = x[j-1] Decrement j by 1 Set x[j] = temp
9
Evaluation of these sorting schemes Primary virtue: simplicity Too inefficient, especially for large lists More efficient sorting algorithms: Heap sort – kind of selection sort Quick sort – kind of exchange sort. One of the most efficient general purpose sorting scheme Shell sort – kind of insertion sort
10
Comparison for list of size 500 SortingTypeSorting time(sec) Simple selection selection69 Heap SortSelection18 Bubble sortExchange165 Quick sortExchange6 Linear insertion Insertion66 ShellInsertion11
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.