直接插入排序
插入排序可以分为直接插入排序、折半插入排序、希尔排序,他们的时间和空间复杂度请参考上一篇博客点击打开链接,本篇文章将介绍插入排序方法中的直接插入排序。
1、思想:直接插入排序的思想就是依次将元素插入到一个有序序列中。假设有待排序列R[0,i-1],将其分为两部分:有序区R[0,j-1],无序区R[j,i-1],如图1所示。排序的过程就是将无序区R[j,i-1]中的元素逐一插入到有序区R[0,j-1]中。假设现有待排序列 { 1, 5, 3, 4, 8, 9, 2 },排序过程如图2所示。
图1
图2
2、代码实现(java)
package sort.baohuajie;
import java.util.Arrays;
/**
* @author 包华杰
* 2017年12月3日
*
*
* 这里使用两种方法实现。本人认为,第二种方法更能体现插入排序的思想
*/
public class DirectInsertSort {
public static void directInsertSort1(int[] array) {
int temp;
int time = 0;
for (int i = 1; i < array.length; i++) {
for (int j = i; j > 0; j--) {
if (array[j] < array[j - 1]) {
temp = array[j - 1];
array[j - 1] = array[j];
array[j] = temp;
}
time++;
System.out.println("第" + time + "次排序结果:"
+ Arrays.toString(array));
}
}
}
public static void directInsertSort2(int[] array) {
int temp=0;
int time = 0;
int j;
for (int i = 1; i < array.length; i++) {
temp=array[i];
j=i-1;
/**
* 用temp和array[j]进行比较,如果temp小于array[j],就让array[j]后移一个位置。
* 直到temp>=array[j]或者j<0
* 最后j+1的位置就是temp要插入的位置
*/
while(j>=0 && temp<array[j]){
array[j+1]=array[j];
j--;
}
array[j+1]=temp;
System.out.println("第" + i + "次排序结果:"
+ Arrays.toString(array));
}
}
public static void main(String[] args) {
// int[] array = { 1, 5, 3, 4, 2 ,0};
int[] array = { 58,46,71,95,84,25,37,58,63,12 };
directInsertSort2(array);
}
}
3、执行结果
第1次排序结果:[46, 58, 71, 95, 84, 25, 37, 58, 63, 12]
第2次排序结果:[46, 58, 71, 95, 84, 25, 37, 58, 63, 12]
第3次排序结果:[46, 58, 71, 95, 84, 25, 37, 58, 63, 12]
第4次排序结果:[46, 58, 71, 84, 95, 25, 37, 58, 63, 12]
第5次排序结果:[25, 46, 58, 71, 84, 95, 37, 58, 63, 12]
第6次排序结果:[25, 37, 46, 58, 71, 84, 95, 58, 63, 12]
第7次排序结果:[25, 37, 46, 58, 58, 71, 84, 95, 63, 12]
第8次排序结果:[25, 37, 46, 58, 58, 63, 71, 84, 95, 12]
第9次排序结果:[12, 25, 37, 46, 58, 58, 63, 71, 84, 95]
【上一篇】常用排序算法
【下一篇】常用排序算法之折半插入排序