50 lines
1.2 KiB
Java
50 lines
1.2 KiB
Java
|
package com.zerroi.leetcode.sort;
|
||
|
|
||
|
|
||
|
public class QuickSort {
|
||
|
public static void main(String[] args) {
|
||
|
QuickSortImpl quickSort = new QuickSortImpl();
|
||
|
int[] arr = {5, 1, 2, 6, 78, 1, 8, 45, 1, 645, 12};
|
||
|
int[] res = quickSort.quickSort(arr, 0, arr.length - 1);
|
||
|
for (int re : res) {
|
||
|
System.out.println(re);
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
class QuickSortImpl {
|
||
|
|
||
|
public int[] quickSort(int[] arr, int left, int right) {
|
||
|
if (left < right) {
|
||
|
int partition = partition(arr, left, right);
|
||
|
quickSort(arr, left, partition - 1);
|
||
|
quickSort(arr, partition + 1, right);
|
||
|
}
|
||
|
return arr;
|
||
|
}
|
||
|
|
||
|
/* 元素交换 */
|
||
|
void swap(int[] nums, int i, int j) {
|
||
|
int tmp = nums[i];
|
||
|
nums[i] = nums[j];
|
||
|
nums[j] = tmp;
|
||
|
}
|
||
|
|
||
|
/* 哨兵划分 */
|
||
|
int partition(int[] nums, int left, int right) {
|
||
|
// 以 nums[left] 为基准数
|
||
|
int i = left;
|
||
|
int j = right;
|
||
|
while (i < j) {
|
||
|
while (i < j && nums[left] >= nums[j]) {
|
||
|
j--;
|
||
|
}
|
||
|
while (i < j && nums[left] <= nums[i]) {
|
||
|
i++;
|
||
|
}
|
||
|
swap(nums, i, j);
|
||
|
}
|
||
|
swap(nums, i, left);
|
||
|
return i;
|
||
|
}
|
||
|
}
|