- 插入排序算法
插入排序(Insertion-Sort)的算法描述是一种简单直观的排序算法。它的工作原理是通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入。
插入排序是通过比较和插入来实现排序的,其排序流程如下:
(1)首先对数组的前两个数据进行从大到小的排序;
(2)接着将第三个数据与排好序的两个数据进行比较,将第三个数据插入合适的位置;
(3)再将第四个数据与前三个进行比较,重复以上步骤,直到最后一个数据插入合适的位置。
下面举一个实例来执行插入排序算法:
5个整型数据118,101,105,127,112,这是一组无序数据。对其执行插入排序过程,步骤如下:
(1)第1次排序,首先对数组的前两个数据118和101排序,由于118大于101,因此将其交换。此时排序后的数据为101、118、 105、 127、 112。
(2)第2次排序,对于第3个数据105,其大于101, 而小于18, 将其插入它们之间。此时排序后的数据为101、105、 118、 127、 112。
(3)第了次排序,对于第4个数据127其大于18将其插入118之后。此时排序后的数据为101、105、118、127、 112。
(4)第4次排序,对于第5个数据12,其大于105,小于18将其插入105和118之间。此时排序后的数据为101、105、 112. 118、 127。
- 实例实现代码:
public static void main(String[] args) {
int[] a = {118,101,105,127,112};
insertionsort(a);
System.out.println("最终排序结果:" + Arrays.toString(a));
}
private static void insertionsort(int[] a) {
int n = 0;
for (int i = 1; i < a.length;i++) {
for(int j = i;j > 0 && a[j-1] > a[j]; j--) {
swap(a,j-1,j);
n++;
System.out.println("第"+n+"步排序结果:"+Arrays.toString(a));
}
}
}
private static void swap(int[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
第1步排序结果:[101, 118, 105, 127, 112]
第2步排序结果:[101, 105, 118, 127, 112]
第3步排序结果:[101, 105, 118, 112, 127]
第4步排序结果:[101, 105, 112, 118, 127]
最终排序结果:[101, 105, 112, 118, 127]
改进算法:
public static void main(String[] args) {
int[] a = {118,101,105,127,112};
insertionsortupper(a);
System.out.println("最终排序结果:" + Arrays.toString(a));
}
private static void insertionsortupper(int[] a) {
int n = 0;
int ret = 0;
int j = 0;
for (int i = 0;i < a.length;i++) {
ret = a[i];
for (j = i;j > 0 && a[j - 1] > ret;j--) {
a[j] = a[j - 1];
}
a[j] = ret;
n++;
System.out.println("第"+n+"步排序结果:"+Arrays.toString(a));
}
}
第1步排序结果:[118, 101, 105, 127, 112]
第2步排序结果:[101, 118, 105, 127, 112]
第3步排序结果:[101, 105, 118, 127, 112]
第4步排序结果:[101, 105, 118, 127, 112]
第5步排序结果:[101, 105, 112, 118, 127]
最终排序结果:[101, 105, 112, 118, 127]