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
Some sorting schemes One classification of sorting schemes consists of three categories: Selection sorts Exchange sorts Insertion sorts
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
Selection sort Original list: Scan the smallest Interchange Continue on sublist
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
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
Insertion sorts Based on the same idea as the algorithms for inserting new element into ordered linked list
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
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
Comparison for list of size 500 SortingTypeSorting time(sec) Simple selection selection69 Heap SortSelection18 Bubble sortExchange165 Quick sortExchange6 Linear insertion Insertion66 ShellInsertion11