/** * 選擇排序的思想: * 每次循環前,數組左邊都是部分有序的序列, * 然后選擇右邊待排元素,將其值保存下來 * 依次和左邊已經排好的元素比較 * 如果小于左邊的元素,就將左邊的元素右移一位 * 直到和最左邊的比較完成,或者待排元素不比左邊元素小 */ package al; public class InsertionSort { public static void main(String[] args) { InsertionSort insertSort = new InsertionSort(); int[] elements = { 14, 77, 21, 9, 10, 50, 43, 14 }; // sort the array insertSort.sort(elements); // print the sorted array for (int i = 0; i < elements.length; i++) { System.out.print(elements[i]); System.out.print(" "); } } /** * @author * @param array 待排數組 */ public void sort(int[] array) { // min to save the minimum element for each round int key; // save current element for(int i=0; i<array.length; i++) { int j = i; // current position key = array[j]; // compare current element while(j > 0 && array[j-1] > key) { array[j] = array[j-1]; //shift it j--; } array[j] = key; } } }
新聞熱點
疑難解答