8 elementary sorts-selection
Transcript of 8 elementary sorts-selection
Selection Sort One of the simplest sorting algorithms Works as follows:
First, find the smallest item in the array, and exchange it with the first entry. Then, find the next smallest item and exchange it with the second entry. Continue in this way until the entire array is sorted.
This method is called selection sort because it works by repeatedly selecting the smallest remaining item.
Selection Sort (cont.)
Selection Sort (cont.)
public static void selectionSort(int[] list, int listLength) { int index; int smallestIndex; int minIndex; int temp;
for (index = 0; index < listLength – 1; index++) { smallestIndex = index; for (minIndex = index + 1; minIndex < listLength; minIndex++) if (list[minIndex] < list[smallestIndex]) smallestIndex = minIndex;
temp = list[smallestIndex]; list[smallestIndex] = list[index]; list[index] = temp; }}
Selection Sort (cont.) It is known that for a list of length N, selection sort makes:
N(N – 1) / 2 key comparisons and N exchanges
Therefore, if N = 1000, then to sort the list selection sort makes about 500,000 key comparisons and about 1000 key exchanges
Selection Sort (cont.)
• Selection Sort on Various Size Arrays:
n Milliseconds
10,000 772
20,000 3,051
30,000 6,846
40,000 12,188
50,000 19,015
60,000 27,359
Obtained with a Pentium processor, 1.2 GHz, Java 5.0, Linux