Java代码 快速排序
时间: 2023-10-16 14:24:28 浏览: 30
以下是Java实现快速排序的代码:
```java
public class QuickSort {
public static void main(String[] args) {
int[] arr = { 10, 7, 8, 9, 1, 5 };
int n = arr.length;
quickSort(arr, 0, n - 1);
System.out.println("排序后的数组:");
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
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);
}
}
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++;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
int temp = arr[i + 1];
arr[i + 1] = arr[high];
arr[high] = temp;
return i + 1;
}
}
```
以上代码使用了递归的方式来实现快速排序,其中 partition() 方法用于将数组分为两部分,并返回枢轴元素(pivot)的位置。在 partition() 方法中,我们选择最后一个元素作为枢轴元素,然后将数组分为两部分:小于等于枢轴元素的部分和大于枢轴元素的部分。最后,我们将枢轴元素放在它应该在的位置上,并返回它的位置。在 quickSort() 方法中,我们首先选择枢轴元素的位置,然后递归地对左右两部分进行快速排序。