Algorithm —— 插入排序
插入排序的基本思想是:每步將一個待排序的記錄,按其關鍵碼值的大小插入前面已經排序的文件中適當位置上,直到全部插入完爲止。
插入排序有個較好理解的例子就是打牌:當我們抽到第一張牌後,再次從牌庫中抽取第二張牌時,我們會排列整理手上的手牌;再次抽到第三張牌,我們會在前兩張牌有序的基礎上再次整理手牌;以此類推。
插入排序Java實現:
// 插入排序
public void insertionSort(int[] array) {
if (array == null || array.length < 1) {
throw new IllegalArgumentException("Array is null or length is short than 1 ");
}
System.out.println("insertionSort:");
int val_j = 0;
for (int i = 1; i < array.length; i++) {// a[i]是一個分隔符.a[i]是正在排序的數,它的左側是已經排過序的有序數組,它的右側是即將要排序的數
for (int j = i; j > 0; j--) {
if (array[j] < array[j - 1]) { // array[j] > array[j-1]: High to Low
val_j = array[j];
array[j] = array[j - 1];// 左右相鄰數調換位置
array[j - 1] = val_j;
}
}
}
}
完整測試代碼:public class AlgorithmTest {
public static void main(String[] args) {
int[] array = { 11, 9, 25, 1, 16, 8, 17, 5 };
AlgorithmTest algorithm = new AlgorithmTest();
algorithm.insertionSort(array);
}
// 插入排序
public void insertionSort(int[] array) {
if (array == null || array.length < 1) {
throw new IllegalArgumentException("Array'length is short than 1 or null");
}
System.out.println("insertionSort:");
arrayPrint(array);
int val_j = 0;
for (int i = 1; i < array.length; i++) {// a[i]是一個分隔符.a[i]是正在排序的數,它的左側是已經排過序的有序數組,它的右側是即將要排序的數
for (int j = i; j > 0; j--) {
if (array[j] < array[j - 1]) { // array[j] > array[j-1]: High to Low
val_j = array[j];
array[j] = array[j - 1];// 左右相鄰數調換位置
array[j - 1] = val_j;
}
}
}
arrayPrint(array);
}
public void arrayPrint(int[] arr) {
System.out.print("[");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + ", ");
}
System.out.println("]");
}
}