企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
## 插入排序 InsertSort * 空间复杂度:O(1) * 时间复杂度:O(n2) ## 思路描述 (把数组分为左和右,左边的默认有顺序,右边的数逐个插入到左边合适的位置) ![](https://box.kancloud.cn/be81c151f38d8923fe1ede31ac530ac4_811x505.gif) ## 例子 ``` old:[13, 7, 4, 6, 9, 24, 12] 1)[7, 13, 4, 6, 9, 24, 12] 2)[7, 4, 13, 6, 9, 24, 12] 2)[4, 7, 13, 6, 9, 24, 12] 3)[4, 7, 6, 13, 9, 24, 12] 3)[4, 6, 7, 13, 9, 24, 12] 4)[4, 6, 7, 9, 13, 24, 12] 6)[4, 6, 7, 9, 13, 12, 24] 6)[4, 6, 7, 9, 12, 13, 24] result:[4, 6, 7, 9, 12, 13, 24] ``` ## Java实现 ~~~ public class InsertSort { public static void main(String[] args) { int[] nums = {13,7,4,6,9,24,12}; System.out.println("old:"+Arrays.toString(nums)); System.out.println("result:"+Arrays.toString(sort(nums))); } // 插入排序 public static int[] sort(int[] nums){ for(int i=0;i<nums.length;i++){ for(int j=i;j>0;j--){ if(nums[j] < nums[j-1]){ swap(nums,j,j-1); System.out.println(i+")"+Arrays.toString(nums)); }else{ break; } } } return nums; } // 交换数组下标 public static void swap(int[] nums,int i,int j){ int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } } ~~~