基础介绍

  • 将一个数组看做成一个有序列表和一个无序列表
  • 初始化有序列表最后一位的下表为: 0
  • 初始化无需列表第一个的下标为: 1
  • 将无需列表的第一个 挨个与有序列表做比较
  • 当无序列表第一个小于当前有序列表的时候 , 将当前有序向后挪一位
  • 继续将无序列表与

image.png


  1. package com.h.排序;
  2. import com.h.util.ArrayUtil;
  3. /**
  4. * 排序算法
  5. * 2022/6/6
  6. */
  7. public class InsertSort {
  8. static int[] array;
  9. InsertSort(int[] array){
  10. this.array = array;
  11. }
  12. //有序列表的下最后一位的下标
  13. static int listIndex = 0;
  14. static int setIndex = 1;
  15. public static void main(String[] args) {
  16. ArrayUtil arrayUtil = new ArrayUtil();
  17. array = arrayUtil.crateArray(100000,500000);
  18. arrayUtil.start();
  19. ArrayUtil.sout(array);
  20. run();
  21. arrayUtil.sout(array);
  22. arrayUtil.end();
  23. }
  24. public static void run(){
  25. while (listIndex < array.length-1) {
  26. int localListIndex = listIndex;
  27. int localSetIndex = setIndex;
  28. //防止数组下标越界
  29. while (localListIndex >= 0) {
  30. if (array[localSetIndex] < array[localListIndex]) {
  31. int saveValue = array[localListIndex];
  32. array[localListIndex] = array[localSetIndex];
  33. array[localSetIndex] = saveValue;
  34. }
  35. localListIndex--;
  36. localSetIndex--;
  37. }
  38. listIndex++;
  39. setIndex++;
  40. }
  41. }
  42. }