基本思想:
直接插入排序的基本思想是:将数组中的所有元素依次跟前面已经排好的元素相比较,如果选择的元素比已排序的元素小,则交换,直到全部元素都比较过为止。
算法描述:
一般来说,插入排序都采用in-place在数组上实现。具体算法描述如下:
①. 从第一个元素开始,该元素可以认为已经被排序
②. 取出下一个元素,在已经排序的元素序列中从后向前扫描
③. 如果该元素(已排序)大于新元素,将该元素移到下一位置
④. 重复步骤3,直到找到已排序的元素小于或者等于新元素的位置
⑤. 将新元素插入到该位置后
⑥. 重复步骤②~⑤
举例加实现:
package com.abc;
import java.util.Arrays;
public class SortAlgorithms {
public static void main(String[] args) {
int[] array = new int[]{5, 3, 9, 1, 6, 4, 10, 2, 8, 7, 15, 3, 2};
System.out.println("Before: " + Arrays.toString(array));
SortAlgorithms.insertionSort(array);
System.out.println("After: " + Arrays.toString(array));
}
public static void insertionSort(int[] arr){
for( int i=0; i<arr.length-1; i++ ) {
for( int j=i+1; j>0; j-- ) {
if( arr[j-1] <= arr[j] )
break;
int temp = arr[j]; //交换操作
arr[j] = arr[j-1];
arr[j-1] = temp;
System.out.println("Sorting: " + Arrays.toString(arr));
}
}
}
}
输出
Before: [5, 3, 9, 1, 6, 4, 10, 2, 8, 7, 15, 3, 2]
Sorting: [3, 5, 9, 1, 6, 4, 10, 2, 8, 7, 15, 3, 2]
Sorting: [3, 5, 1, 9, 6, 4, 10, 2, 8, 7, 15, 3, 2]
Sorting: [3, 1, 5, 9, 6, 4, 10, 2, 8, 7, 15, 3, 2]
Sorting: [1, 3, 5, 9, 6, 4, 10, 2, 8, 7, 15, 3, 2]
Sorting: [1, 3, 5, 6, 9, 4, 10, 2, 8, 7, 15, 3, 2]
Sorting: [1, 3, 5, 6, 4, 9, 10, 2, 8, 7, 15, 3, 2]
Sorting: [1, 3, 5, 4, 6, 9, 10, 2, 8, 7, 15, 3, 2]
Sorting: [1, 3, 4, 5, 6, 9, 10, 2, 8, 7, 15, 3, 2]
Sorting: [1, 3, 4, 5, 6, 9, 2, 10, 8, 7, 15, 3, 2]
Sorting: [1, 3, 4, 5, 6, 2, 9, 10, 8, 7, 15, 3, 2]
Sorting: [1, 3, 4, 5, 2, 6, 9, 10, 8, 7, 15, 3, 2]
Sorting: [1, 3, 4, 2, 5, 6, 9, 10, 8, 7, 15, 3, 2]
Sorting: [1, 3, 2, 4, 5, 6, 9, 10, 8, 7, 15, 3, 2]
Sorting: [1, 2, 3, 4, 5, 6, 9, 10, 8, 7, 15, 3, 2]
Sorting: [1, 2, 3, 4, 5, 6, 9, 8, 10, 7, 15, 3, 2]
Sorting: [1, 2, 3, 4, 5, 6, 8, 9, 10, 7, 15, 3, 2]
Sorting: [1, 2, 3, 4, 5, 6, 8, 9, 7, 10, 15, 3, 2]
Sorting: [1, 2, 3, 4, 5, 6, 8, 7, 9, 10, 15, 3, 2]
Sorting: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 3, 2]
Sorting: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 3, 15, 2]
Sorting: [1, 2, 3, 4, 5, 6, 7, 8, 9, 3, 10, 15, 2]
Sorting: [1, 2, 3, 4, 5, 6, 7, 8, 3, 9, 10, 15, 2]
Sorting: [1, 2, 3, 4, 5, 6, 7, 3, 8, 9, 10, 15, 2]
Sorting: [1, 2, 3, 4, 5, 6, 3, 7, 8, 9, 10, 15, 2]
Sorting: [1, 2, 3, 4, 5, 3, 6, 7, 8, 9, 10, 15, 2]
Sorting: [1, 2, 3, 4, 3, 5, 6, 7, 8, 9, 10, 15, 2]
Sorting: [1, 2, 3, 3, 4, 5, 6, 7, 8, 9, 10, 15, 2]
Sorting: [1, 2, 3, 3, 4, 5, 6, 7, 8, 9, 10, 2, 15]
Sorting: [1, 2, 3, 3, 4, 5, 6, 7, 8, 9, 2, 10, 15]
Sorting: [1, 2, 3, 3, 4, 5, 6, 7, 8, 2, 9, 10, 15]
Sorting: [1, 2, 3, 3, 4, 5, 6, 7, 2, 8, 9, 10, 15]
Sorting: [1, 2, 3, 3, 4, 5, 6, 2, 7, 8, 9, 10, 15]
Sorting: [1, 2, 3, 3, 4, 5, 2, 6, 7, 8, 9, 10, 15]
Sorting: [1, 2, 3, 3, 4, 2, 5, 6, 7, 8, 9, 10, 15]
Sorting: [1, 2, 3, 3, 2, 4, 5, 6, 7, 8, 9, 10, 15]
Sorting: [1, 2, 3, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15]
Sorting: [1, 2, 2, 3, 3, 4, 5, 6, 7, 8, 9, 10, 15]
After: [1, 2, 2, 3, 3, 4, 5, 6, 7, 8, 9, 10, 15]