插入排序是算法入门的基础算法之一,它的原理类似于扑克牌插入的过程。
步骤:
1、从第二个位置逐个与前面元素进行比较
2、逐步替换position位置
3、直到找到比当前元素小的元素,将当前元素放到position位置上
具体代码过程:
public class Insertsort {
public static void main(String[] args) {
int[] array = new int[] { 12, 5, 74, 325, 96, 746 };
Insertsort(array);
print(array);
}
public static void print(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
public static void Insertsort(int[] array) {
if (array == null || array.length < 2) {
return;
}
for (int i = 1; i < array.length; i++) {
<span style="white-space:pre"> </span>//保存当前的值(相当于扑克中刚摸到的牌)
int currentValue = array[i];
int position = i;
// 遍历替换,从后面查找,直到找到此位置值小于当前值
// position 保存了 i 应存储的光标位置
for (int j = i - 1; j >= 0; j--) {
if (array[j] > currentValue) {
array[j + 1] = array[j];
position -= 1;
} else {
break;
}
}
array[position] = currentValue;
}
}
}