Arrays
More skills
Sort
Sorting is a common task in computer programming. Many different algorithms have been developed for sorting.
Selection sorting
Selection sort finds the largest number in the list and places it last. It then finds the largest number remaining and places it next to last, and so on until the list contains only a single number. Figure 6.17 shows how to sort the list {2, 9, 5, 4, 8, 1, 6} using selection sort.
/** The method for sorting the numbers */ public static void selectionSort(double[] list) { for (int i = list.length - 1; i >= 1; i--) { // Find the maximum in the list[0..i] double currentMax = list[0]; int currentMaxIndex = 0; for (int j = 1; j <= i; j++) { if (currentMax < list[j]) { currentMax = list[j]; currentMaxIndex = j; } } // Swap list[i] with list[currentMaxIndex] if necessary; if (currentMaxIndex != i) { list[currentMaxIndex] = list[i]; list[i] = currentMax; } } }
Insertion sort
The insertion sort algorithm sorts a list of values by repeatedly inserting an unsorted element into a sorted sublist until the whole list is sorted.
The insertion sort algorithm sorts a list of values by repeatedly inserting an unsorted element into a sorted sublist until the whole list is sorted.