选择排序的代码实现:
?
package ganggong.algorithm.sort; public class SortTest { public static void main(String[] args) { SortTest sortTest = new SortTest(); int[] array = sortTest.generateArray(7); System.out.print("unsorted array: "); sortTest.printArray(array); sortTest.selectionSort(array); } private void selectionSort(int[] array) { System.out.println("\nselection sort begin:"); for (int i = 0; i < array.length; i++) { printArray(array); System.out.print(" ----> "); int minIndex = i; for (int j = i; j < array.length; j++) { if (array[j] < array[minIndex]) { minIndex = j; } } int t = array[i]; array[i] = array[minIndex]; array[minIndex] = t; printArray(array); System.out.println(); } assertSorted(array); } private int[] generateArray(int size) { int[] array = new int[size]; for (int i = 0; i < array.length; i++) { array[i] = (int) (Math.random() * 10); } return array; } private void printArray(int[] array) { for (int i = 0; i < array.length; i++) { System.out.print(array[i] + "\t"); } } private void assertSorted(int[] array) { boolean sorted = true; for (int i = 0; i < array.length - 1; i++) { if (array[i] > array[i + 1]) { sorted = false; break; } } if (!sorted) { throw new RuntimeException("Not sorted"); } } }
?
结果如下:
?
原文:http://gonggang.iteye.com/blog/2190360