直接插入排序是一种最简单的排序方法。
基本操作:
一列数据,将未排序序列的第一个数据插入已排序序列的合适位置。
public class Insert {
public static void main(String[] args) {
int[] m = {3, 1, 5, -2, 9, 7, 4};
for (int i = 1; i < m.length; i++) {
int t = m[i]; // 将未排序序列中的第一个数用t记录
int j = i - 1;
for ( ; j >= 0; j--) {
if (t >= m[j]) { // 如果遇到不小于的数、则跳出判断
break;
} else { // 若遇到比t小的、将序列已排序列后移
m[j + 1] = m[j];
}
}
m[j + 1] = t; // 找到了m[i]的合适位置、插入
}
System.out.println(java.util.Arrays.toString(m));
}
}
实际使用时,我比较喜欢不设置监视哨,直接将要插入的数据与前一个比较的数交换,然后接着比较。
public class InsertSort {
public static void main(String[] args) {
int[] m = {3, 1, 5, -2, 9, 7, 4};
for (int i = 1; i < m.length; i++) {
for (int j = i - 1; j >= 0; j--) {
if (m[j+1] >= m[j]) {
break;
}
if (m[j+1] < m[j]) {
int t = m[j];
m[j] = m[j+1];
m[j+1] = t;
}
}
}
System.out.println(java.util.Arrays.toString(m));
}
}