在Java中,快速排序可以使用多种不同的实现方法,其中一些常用的方法包括:
- 递归实现:
public static void quickSort(int[] nums, int low, int high) {
if (low < high) {
int pivot = partition(nums, low, high);
quickSort(nums, low, pivot - 1);
quickSort(nums, pivot + 1, high);
}
}
private static int partition(int[] nums, int low, int high) {
int pivot = nums[high];
int i = low - 1;
for (int j = low; j <= high - 1; j++) {
if (nums[j] <= pivot) {
i++;
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
int temp = nums[i + 1];
nums[i + 1] = nums[high];
nums[high] = temp;
return i + 1;
}