import com.alibaba.fastjson.JSON; import lombok.extern.slf4j.Slf4j; /** * @author: Small sun shine * @Description: * @date: 2021/6/20 9:40 上午 */ @Slf4j public class IntSort { private static int[] source = new int[]{5, 8, 2, 4, 3, 6, 9, 2,2,4,5,6,43,0,87,45}; private static int totalCount = 0; private static int count = 0; public static void main(String[] args) { System.out.println("原始数组数据:" + JSON.toJSONString(check(source))); System.out.println("排序后数据:" + JSON.toJSONString(check(source))); System.out.println("总交换次数:" + count); System.out.println("总比较次数:" + totalCount); } public static int[] check(int[] source) { //如果数组为null或长度等于1,就直接返回 if (null == source || source.length == 1) { return source; } //进行插入排序 int length = source.length; for (int i = 1; i < length; i++) { int data = source[i]; int j = i - 1; for (; j >= 0; j--) { totalCount++; if (source[j] > data) { count++; source[j + 1] = source[j]; } else { break; } } source[j + 1] = data; String str = String.format("第%d次排序后的次序为:%s", i, JSON.toJSONString(source)); System.out.println(str); } return source; } }