给出java语言的快速排序算法
时间: 2023-08-20 14:05:34 浏览: 47
Java语言的快速排序算法可以如下实现:
```java
public class QuickSort {
public static void main(String[] args) {
int[] arr = {5, 2, 8, 7, 1, 3};
quickSort(arr, 0, arr.length - 1);
System.out.println(Arrays.toString(arr));
}
public static void quickSort(int[] arr, int low, int high) {
if (low < high) {
int pivot = partition(arr, low, high);
quickSort(arr, low, pivot - 1);
quickSort(arr, pivot + 1, high);
}
}
public 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;
}
public static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
```
这是一个基于递归的快速排序算法实现,通过选择一个pivot(基准值),将数组分为小于pivot的左子数组和大于pivot的右子数组,然后对左右子数组分别进行递归排序。最后将左子数组、pivot和右子数组合并即可得到排序后的数组。