java 写一个快速排序
时间: 2023-07-06 13:35:01 浏览: 37
好的,下面给出Java实现的快速排序代码:
```
public class QuickSort {
public static void quickSort(int[] arr, int low, int high) {
if (low < high) {
int pivotIndex = partition(arr, low, high);
quickSort(arr, low, pivotIndex - 1);
quickSort(arr, pivotIndex + 1, high);
}
}
private static int partition(int[] arr, int low, int high) {
int pivot = arr[high];
int i = low - 1;
for (int j = low; j < high; j++) {
if (arr[j] < pivot) {
i++;
swap(arr, i, j);
}
}
swap(arr, i + 1, high);
return i + 1;
}
private static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
```
使用方法:
```
int[] arr = {4, 3, 6, 1, 2, 5};
QuickSort.quickSort(arr, 0, arr.length - 1);
System.out.println(Arrays.toString(arr));
```
输出结果为:[1, 2, 3, 4, 5, 6]
阅读全文