💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
## 冒泡排序 BubbleSort * 空间复杂度:O(1) * 时间复杂度:O(n2) ## 思路描述 2重循环,内循环数比较外层值小于内层值,则交换;如果内层比较完了没有出现交换则说明已经排好顺序,则提前退出。 ![](https://box.kancloud.cn/b7d216a5b292cf3a5412bbc7fbb56a9e_826x257.gif) ## 例子 ``` old:[1, 7, 4, 6, 9, 24, 12] 0)[7, 1, 4, 6, 9, 24, 12] 0)[9, 1, 4, 6, 7, 24, 12] 0)[24, 1, 4, 6, 7, 9, 12] 1)[1, 24, 4, 6, 7, 9, 12] 2)[1, 4, 24, 6, 7, 9, 12] 3)[1, 4, 6, 24, 7, 9, 12] 4)[1, 4, 6, 7, 24, 9, 12] 5)[1, 4, 6, 7, 9, 24, 12] 6)[1, 4, 6, 7, 9, 12, 24] result:[1, 4, 6, 7, 9, 12, 24] ``` ## Java实现 ~~~ public class BubbleSort { public static void main(String[] args) { int[] nums = {1,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){ boolean hasChanged = true; for(int i=0;i<nums.length && hasChanged;i++){ hasChanged = false; for(int j=0;j<nums.length;j++){ if(nums[i] < nums[j]){ swap(nums,i,j); hasChanged = true; System.out.println(i+")"+Arrays.toString(nums)); } } } return nums; } // 交换数组下标 public static void swap(int[] nums,int i,int j){ int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } } ~~~