写一段java快速排序代码
时间: 2023-10-14 11:28:59 浏览: 97
以下是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("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;
}
}
```
该代码使用递归实现快速排序。在 `quickSort` 方法中,首先选择一个基准元素,然后将数组划分为两个子数组,其中一个子数组的元素都比基准元素小,另一个子数组的元素都比基准元素大。然后对这两个子数组递归地应用快速排序算法。`partition` 方法用于划分数组,并返回基准元素的索引。
阅读全文
相关推荐















