插入排序,就是通过比较把元素放到对应的位置,看下图,麻将大家应该都打过,摸到五万后,将五万放在原来六万所在的位置,将六万及后面的元素右移.
代码体现:
public class ArithmeticTest {
/**
* 选择排序
*/
public static void main(String[] args) {
int[] dest = new int[]{12, 3, 11, 56, 37, 9, 28};
printArray(dest);
System.out.println("---------------------");
int[] result = insertSort(dest);
printArray(result);
}
private static int[] insertSort(int[] nums) {
if (nums.length == 0) {
return nums;
}
//当前待排序的元素
int currentValue;
//循环遍历数组长度,从索引为0 开始
for (int i = 0; i < nums.length - 1; i++) {
//已排序完成的索引位置
int preIndex = i;
currentValue = nums[preIndex + 1];
System.out.println("待排序元素索引:" + (i + 1) + ",值为:" + currentValue + ",已排序元素索引:" + preIndex);
//在已排序过的元素中寻找合适位置,如果当前元素比比较的元素小,将比较的元素后移一位
while (preIndex >= 0 && currentValue < nums[preIndex]) {
//当前元素右移一位
nums[preIndex + 1] = nums[preIndex];
//倒叙查找
preIndex--;
printArray(nums);
}
//循环结束,表示已找到了适合当前元素的位置
nums[preIndex + 1] = currentValue;
System.out.println("本轮排序后的数组:");
printArray(nums);
}
return nums;
}
private static void printArray(int[] dest) {
for (int i = 0; i < dest.length; i++) {
System.out.print(dest[i] + " ");
}
System.out.println(" ");
}
}
打印结果:
12 3 11 56 37 9 28
待排序元素索引:1,值为:3,已排序元素索引:0
12 12 11 56 37 9 28
本轮排序后的数组:
3 12 11 56 37 9 28
待排序元素索引:2,值为:11,已排序元素索引:1
3 12 12 56 37 9 28
本轮排序后的数组:
3 11 12 56 37 9 28
待排序元素索引:3,值为:56,已排序元素索引:2
本轮排序后的数组:
3 11 12 56 37 9 28
待排序元素索引:4,值为:37,已排序元素索引:3
3 11 12 56 56 9 28
本轮排序后的数组:
3 11 12 37 56 9 28
待排序元素索引:5,值为:9,已排序元素索引:4
3 11 12 37 56 56 28
3 11 12 37 37 56 28
3 11 12 12 37 56 28
3 11 11 12 37 56 28
本轮排序后的数组:
3 9 11 12 37 56 28
待排序元素索引:6,值为:28,已排序元素索引:5
3 9 11 12 37 56 56
3 9 11 12 37 37 56
本轮排序后的数组:
3 9 11 12 28 37 56
3 9 11 12 28 37 56