100 likes | 268 Views
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
E N D
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
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 • 67 33 21 84 49 50 75 • 67 21 84 49 50 75 • 67 21 84 49 50 75 • 3367 21 84 49 50 75 • 21 3367 84 49 50 75 • 21 336784 49 50 75 • 21 336784 49 50 75 • 21 3349 6784 50 75 • 21 3349 506784 75 • 21 3349 50677584
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