2019-06-27
把新的数据插入到已经排好的数据列中
对于一个无序数组而言,从第二个数开始选定并向后遍历,比较第二个数与它前面的数,若小于它前面的数则把他前面的数向后移动,最后把该数放入合适的位置。
代码实现
/*
* @Date 2019/8/7 8:33
* @Description
* 1.将第一个数和第二个数排序,然后构成一个有序序列
* 2.将第三个数插入进去,构成一个新的有序序列。
* 3.对第四个数、第五个数……直到最后一个数,重复第二步。
**/
public class InsertSort {
public void insertSort(int[] a) {
int length = a.length;//数组长度,将这个提取出来是为了提高速度
int insertNum;//要插入的数
//i从第二个数开始向后遍历
for (int i = 1; i < length; i++) {
insertNum = a[i];//要插入的数
int j = i - 1;
//序列从后到前循环,将大于insertNum的数向后移动一位
while (j >= 0 && a[j] > insertNum) {
a[j + 1] = a[j];//元素向后移动一位
j--;
}
a[j + 1] = insertNum;//将要插入的数插入到合适的位置
}
System.out.println(Arrays.toString(a));
}
@Test
public void testInsertSort() {
int[] a = {35, 11, 24, 52, 77, 69, 8, 3, 6, 62};
int[] b = {7, 9, 3, 2, 5, 8, 6};
insertSort(a);
insertSort(b);
}
}
/*
Output:
[3, 6, 8, 11, 24, 35, 52, 62, 69, 77]
[2, 3, 5, 6, 7, 8, 9]
*/