用Java写出快速排序的程序
时间: 2023-05-18 10:04:46 浏览: 92
用java实现快速排序
以下是 Java 中快速排序的代码示例:
```
import java.util.Arrays;
public class QuickSort {
public static void main(String[] args) {
int[] nums = {4, 2, 9, 6, 23, 12, 34, 0, 1};
quickSort(nums, 0, nums.length-1);
System.out.println(Arrays.toString(nums));
}
public static void quickSort(int[] nums, int low, int high) {
if (nums == null || nums.length == 0)
return;
if (low >= high)
return;
int middle = low + (high - low) / 2;
int pivot = nums[middle];
int i = low, j = high;
while (i <= j) {
while (nums[i] < pivot) {
i++;
}
while (nums[j] > pivot) {
j--;
}
if (i <= j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
i++;
j--;
}
}
if (low < j)
quickSort(nums, low, j);
if (high > i)
quickSort(nums, i, high);
}
}
```
这个代码使用了递归的方法,从数组的两端不断逼近,直到所有元素都被正确地排序。
阅读全文