把上面的数组用java写一份快速排序
时间: 2023-03-05 19:27:18 浏览: 56
好的,以下是用 Java 写的快速排序:
```java
public class QuickSort {
public void quickSort(int[] nums) {
quickSort(nums, 0, nums.length - 1);
}
private void quickSort(int[] nums, int start, int end) {
if (start >= end) {
return;
}
int pivotIndex = partition(nums, start, end);
quickSort(nums, start, pivotIndex - 1);
quickSort(nums, pivotIndex + 1, end);
}
private int partition(int[] nums, int start, int end) {
int pivot = nums[end];
int i = start - 1;
for (int j = start; j < end; j++) {
if (nums[j] < pivot) {
i++;
swap(nums, i, j);
}
}
swap(nums, i + 1, end);
return i + 1;
}
private void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
```
使用方法如下:
```java
int[] nums = {3, 7, 8, 5, 2, 1, 9, 5, 4};
QuickSort sorter = new QuickSort();
sorter.quickSort(nums);
System.out.println(Arrays.toString(nums));
```
输出结果如下:
```
[1, 2, 3, 4, 5, 5, 7, 8, 9]
```
希望对你有帮助!
阅读全文