Java數據構造及算法實例:拔出排序 Insertion Sort。本站提示廣大學習愛好者:(Java數據構造及算法實例:拔出排序 Insertion Sort)文章只能為提供參考,不一定能成為您想要的結果。以下是Java數據構造及算法實例:拔出排序 Insertion Sort正文
/**
* 選擇排序的思惟:
* 每次輪回前,數組右邊都是部門有序的序列,
* 然後選擇左邊待排元素,將其值保留上去
* 順次和右邊曾經排好的元素比擬
* 假如小於右邊的元素,就將右邊的元素右移一名
* 直到和最右邊的比擬完成,或許待排元素不比右邊元素小
*/
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;
}
}
}