用Java代码写一段快速排序。
时间: 2023-05-30 09:03:24 浏览: 76
以下是使用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("Sorted array:");
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;
}
}
```
在这个代码中,我们首先定义了一个 `main` 函数,它包含一个整型数组 `arr`,并且使用 `quickSort` 函数对其进行排序。`quickSort` 函数是我们的主要函数,它接受三个参数:要排序的数组,数组的最低索引和最高索引。在 `quickSort` 函数中,我们使用 `partition` 函数来选择一个 `pivot`(通常选择最后一个元素),并将 `arr` 分成两个子数组,分别包含小于 `pivot` 和大于 `pivot` 的元素。然后,我们递归地对这两个子数组调用 `quickSort` 函数,直到子数组的大小为 1 或 0。`partition` 函数是实现快速排序算法的关键。它使用两个指针 `i` 和 `j` 来遍历数组,并将小于 `pivot` 的元素放在左边,大于 `pivot` 的元素放在右边。最后,它将 `pivot` 放在分割点,并返回分割点的索引。在 `main` 函数中,我们输出排序后的数组。