1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| public class SelectionSortDemo { public static void main(String[] args) { int[] sample = new Random().ints(0, 100).limit(10).toArray(); System.out.println("Origin: " + Arrays.toString(sample));
selectionSort(sample); System.out.println("After: " + Arrays.toString(sample)); }
private static void selectionSort(int[] sample) { for (int i = 0; i < sample.length - 1; i++) { int max_idx = i; for (int j = i; j < sample.length; j++) { if (sample[max_idx] < sample[j]) { max_idx = j; }
} if (max_idx != i) { swap(sample, i, max_idx); } } }
private static void swap(int[] sample, int i, int j) { int tmp = sample[i]; sample[i] = sample[j]; sample[j] = tmp; } }
|