思路
将数组分为有序区间 和 无排序区间,默认第一个为有序区间,依次从左到右,左边第一个为有序区间,取无排序区间第一个数,与有序区间末尾数进行比较,如果小则互换位置,直到该树找到有序区间的合适位置为止,一直轮询此操作
java 示例
package com.example.demo.sort;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ArrayUtil;
import java.util.Collections;
import java.util.Random;
public class DirectInsertionSort {
public static void main(String[] args) {
int num = 20;
int[] nums = new int[num];
Random r = new Random(1);
for (int i = 0; i < num; i++) {
nums[i] = r.nextInt(100);
}
DirectInsertionSort directInsertionSort = new DirectInsertionSort();
directInsertionSort.sort(nums);
}
public void sort(int[] num) {
for (int i = 0; i < num.length - 1; i++) {
for (int end = i; end >= 0; end--) {
if (num[end + 1] < num[end]) {
int temp = num[end];
num[end] = num[end + 1];
num[end + 1] = temp;
} else {
break;
}
}
System.out.println(String.format("有序,无序情况 [%s] - [%s]", CollectionUtil.join(Collections.singleton(ArrayUtil.sub(num, 0, i + 1)), ","), CollectionUtil.join(Collections.singleton(ArrayUtil.sub(num, i + 1, num.length)), ",")));
}
}
}
运行结果
有序,无序情况 [85] - [88,47,13,54,4,34,6,78,48,69,73,17,63,62,34,92,62,96,89]
有序,无序情况 [47,85] - [88,13,54,4,34,6,78,48,69,73,17,63,62,34,92,62,96,89]
有序,无序情况 [13,47,85] - [88,54,4,34,6,78,48,69,73,17,63,62,34,92,62,96,89]
有序,无序情况 [13,47,54,85] - [88,4,34,6,78,48,69,73,17,63,62,34,92,62,96,89]
有序,无序情况 [4,13,47,54,85] - [88,34,6,78,48,69,73,17,63,62,34,92,62,96,89]
有序,无序情况 [4,13,34,47,54,85] - [88,6,78,48,69,73,17,63,62,34,92,62,96,89]
有序,无序情况 [4,6,13,34,47,54,85] - [88,78,48,69,73,17,63,62,34,92,62,96,89]
有序,无序情况 [4,6,13,34,47,54,78,85] - [88,48,69,73,17,63,62,34,92,62,96,89]
有序,无序情况 [4,6,13,34,47,48,54,78,85] - [88,69,73,17,63,62,34,92,62,96,89]
有序,无序情况 [4,6,13,34,47,48,54,69,78,85] - [88,73,17,63,62,34,92,62,96,89]
有序,无序情况 [4,6,13,34,47,48,54,69,73,78,85] - [88,17,63,62,34,92,62,96,89]
有序,无序情况 [4,6,13,17,34,47,48,54,69,73,78,85] - [88,63,62,34,92,62,96,89]
有序,无序情况 [4,6,13,17,34,47,48,54,63,69,73,78,85] - [88,62,34,92,62,96,89]
有序,无序情况 [4,6,13,17,34,47,48,54,62,63,69,73,78,85] - [88,34,92,62,96,89]
有序,无序情况 [4,6,13,17,34,34,47,48,54,62,63,69,73,78,85] - [88,92,62,96,89]
有序,无序情况 [4,6,13,17,34,34,47,48,54,62,63,69,73,78,85,88] - [92,62,96,89]
有序,无序情况 [4,6,13,17,34,34,47,48,54,62,62,63,69,73,78,85,88] - [92,96,89]
有序,无序情况 [4,6,13,17,34,34,47,48,54,62,62,63,69,73,78,85,88,92] - [96,89]
有序,无序情况 [4,6,13,17,34,34,47,48,54,62,62,63,69,73,78,85,88,89,92] - [96]
|