思想 堆排序核心算法 要求为使用常数空间,则符合要求的有冒泡排序、选择排序、插入排序、希尔排序、堆排序。本次采用堆排序。因为限制为2,计数排序应该效果也不错。代码 class Solution { public static void swap(int[] a, int i, int j){ int temp; temp = a[i]; a[i] = a[j]; a[j] = temp; } public void sortColors(int[] nums) { int len = nums.length; int root = 0; int i; int j = len - 1; while(j > 0){ i = j; while (i > 0){ if((i-2)%2 == 1 || i ==1) { root = (i - 1) / 2; i -= 1; if(nums[root] < nums[root*2 + 1]) swap(nums,root,root*2+1); } else { root = (i - 2) / 2; i -= 2; if(nums[root*2+1] < nums[root*2+2]){ if(nums[root] < nums[root*2+2]) swap(nums,root,root *2+2); }else if(nums[root] < nums[root*2+1]) swap(nums,root,root *2+1); } } swap(nums,0,j); j--; } } }