基本介绍
插入式排序属于内部排序法,是对待排序的元素以插入的方式找寻该元素的适当位置,以达到排序的目的。 插入排序(Insertion Sorting)的基本思想是:把n个待排序的元素看成为一个有序表和一个无序表,开始时有序表中只包含一个元素,无序表中包含有n-1个元素,排序过程中每次从无序表中取出第一个元素,把它的排序码依次和有序表元素的排序码进行比较,将它插入到有序表中的适当位置,使之成为新的有序表。
推导过程
原始数组:17,3,25,14,20,9
3,17,25,14,20,9
3,17,25,14,20,9
3,14,17,25,20,9
3,14,17,20,25,9
3,9,14,17,20,25
代码分解
public class InsertSort {
public static void main(String[] args) {
int[] arr = {17, 3, 25,14,20,9};
insertSort(arr);
}
public static void insertSort(int[] arr) {
int insertVal = arr[1];
int insertIndex = 1 - 1;
while ((insertIndex >= 0) && (insertVal < arr[insertIndex])) {
arr[insertIndex + 1] = arr[insertIndex];
insertIndex--;
}
if ((insertIndex + 1) != 1) {
arr[insertIndex + 1] = insertVal;
}
System.out.println("第一趟排序结果:" + Arrays.toString(arr));
insertVal = arr[2];
insertIndex = 2 - 1;
while ((insertIndex >= 0) && (insertVal < arr[insertIndex])) {
arr[insertIndex + 1] = arr[insertIndex];
insertIndex--;
}
if ((insertIndex + 1) != 2) {
arr[insertIndex + 1] = insertVal;
}
System.out.println("第二趟排序结果:" + Arrays.toString(arr));
insertVal = arr[3];
insertIndex = 3 - 1;
while ((insertIndex >= 0) && (insertVal < arr[insertIndex])) {
arr[insertIndex + 1] = arr[insertIndex];
insertIndex--;
}
if ((insertIndex + 1) != 3) {
arr[insertIndex + 1] = insertVal;
}
System.out.println("第三趟排序结果:" + Arrays.toString(arr));
insertVal = arr[4];
insertIndex = 4 - 1;
while ((insertIndex >= 0) && (insertVal < arr[insertIndex])) {
arr[insertIndex + 1] = arr[insertIndex];
insertIndex--;
}
if ((insertIndex + 1) != 4) {
arr[insertIndex + 1] = insertVal;
}
System.out.println("第四趟排序结果:" + Arrays.toString(arr));
insertVal = arr[5];
insertIndex = 5 - 1;
while ((insertIndex >= 0) && (insertVal < arr[insertIndex])) {
arr[insertIndex + 1] = arr[insertIndex];
insertIndex--;
}
if ((insertIndex + 1) != 5) {
arr[insertIndex + 1] = insertVal;
}
System.out.println("第五趟排序结果:" + Arrays.toString(arr));
}
}
运行结果 第一趟排序结果:[3, 17, 25, 14, 20, 9] 第二趟排序结果:[3, 17, 25, 14, 20, 9] 第三趟排序结果:[3, 14, 17, 25, 20, 9] 第四趟排序结果:[3, 14, 17, 20, 25, 9] 第五趟排序结果:[3, 9, 14, 17, 20, 25]
优化代码
public class InsertSort {
public static void main(String[] args) {
int[] arr = {17, 3, 25,14,20,9};
insertSort(arr);
}
public static void insertSort(int[] arr) {
for (int i = 1; i < arr.length; i++) {
int insertVal = arr[i];
int insertIndex = i - 1;
while ((insertIndex >= 0) && (insertVal < arr[insertIndex])) {
arr[insertIndex + 1] = arr[insertIndex];
insertIndex--;
}
if ((insertIndex + 1) != i) {
arr[insertIndex + 1] = insertVal;
}
}
}
}
|