插入排序就是每一步都将一个待排数据按其大小插入到已经排序的数据中的适当位置,直到全部插入完毕。
插入排序方法分直接插入排序和折半插入排序两种,这里只介绍直接插入排序,折半插入排序留到“查找”内容中进行。
图1演示了对4个元素进行直接插入排序的过程,共需要(a),(b),(c)三次插入。
public class InsertSort {
public static void main(String[] args) {
int[] arr = {8, 2, 4, 9, 3, 6, 7, 10};
insertSort(arr);
}
//辅助函数
public static void dumpArray(int[] arr) {
for(int index = 0; index < arr.length; index++) {
System.out.print(arr[index] + " ");
}
System.out.println("");
}
public static void insertSort(int[] arr) {
dumpArray(arr); //输出原始数组
for(int index = 1; index < arr.length; index++) {
int subIndex = index;
int currentData = arr[index]; //等待插入的数据
while((subIndex > 0) && arr[subIndex - 1] > currentData) {
arr[subIndex] = arr[subIndex - 1];
subIndex--;
}
arr[subIndex] = currentData; //插入到合适位置
//每次排序后也输出
dumpArray(arr);
}
}
}