publicvoidrandomizedQuicksort(int[] nums, int l, int r) { if (l < r) { intpos= randomizedPartition(nums, l, r); randomizedQuicksort(nums, l, pos - 1); randomizedQuicksort(nums, pos + 1, r); } }
publicintrandomizedPartition(int[] nums, int l, int r) { inti=newRandom().nextInt(r - l + 1) + l; // 随机选一个作为我们的主元 swap(nums, r, i); return partition(nums, l, r); }
publicintpartition(int[] nums, int l, int r) { intpivot= nums[r]; inti= l - 1; for (intj= l; j <= r - 1; ++j) { if (nums[j] <= pivot) { i = i + 1; swap(nums, i, j); } } swap(nums, i + 1, r); return i + 1; }
privatevoidswap(int[] nums, int i, int j) { inttemp= nums[i]; nums[i] = nums[j]; nums[j] = temp; } }
复杂度分析
时间复杂度:基于随机选取主元的快速排序时间复杂度为期望 O(n\log n),其中 n 为数组的长度。详细证明过程可以见《算法导论》第七章,这里不再大篇幅赘述。
classSolution { voidmaxHeapify(vector<int>& nums, int i, int len){ for (; (i << 1) + 1 <= len;) { int lson = (i << 1) + 1; int rson = (i << 1) + 2; int large; if (lson <= len && nums[lson] > nums[i]) { large = lson; } else { large = i; } if (rson <= len && nums[rson] > nums[large]) { large = rson; } if (large != i) { swap(nums[i], nums[large]); i = large; } else { break; } } } voidbuildMaxHeap(vector<int>& nums, int len){ for (int i = len / 2; i >= 0; --i) { maxHeapify(nums, i, len); } } voidheapSort(vector<int>& nums){ int len = (int)nums.size() - 1; buildMaxHeap(nums, len); for (int i = len; i >= 1; --i) { swap(nums[i], nums[0]); len -= 1; maxHeapify(nums, 0, len); } } public: vector<int> sortArray(vector<int>& nums){ heapSort(nums); return nums; } };
publicvoidheapSort(int[] nums) { intlen= nums.length - 1; buildMaxHeap(nums, len); for (inti= len; i >= 1; --i) { swap(nums, i, 0); len -= 1; maxHeapify(nums, 0, len); } }
publicvoidbuildMaxHeap(int[] nums, int len) { for (inti= len / 2; i >= 0; --i) { maxHeapify(nums, i, len); } }
publicvoidmaxHeapify(int[] nums, int i, int len) { for (; (i << 1) + 1 <= len;) { intlson= (i << 1) + 1; intrson= (i << 1) + 2; int large; if (lson <= len && nums[lson] > nums[i]) { large = lson; } else { large = i; } if (rson <= len && nums[rson] > nums[large]) { large = rson; } if (large != i) { swap(nums, i, large); i = large; } else { break; } } }
privatevoidswap(int[] nums, int i, int j) { inttemp= nums[i]; nums[i] = nums[j]; nums[j] = temp; } }
classSolution: defmax_heapify(self, heap, root, heap_len): p = root while p * 2 + 1 < heap_len: l, r = p * 2 + 1, p * 2 + 2 if heap_len <= r or heap[r] < heap[l]: nex = l else: nex = r if heap[p] < heap[nex]: heap[p], heap[nex] = heap[nex], heap[p] p = nex else: break defbuild_heap(self, heap): for i inrange(len(heap) - 1, -1, -1): self.max_heapify(heap, i, len(heap))