分治法进行快速排序,Java代码
时间: 2024-10-14 07:03:03 浏览: 33
分治法是一种常用的算法设计策略,其中快速排序是一种经典的基于分治的排序算法。它的基本思想是将一个大问题分解成几个小问题,然后递归地解决每个小问题,最后合并结果。下面是使用Java实现的快速排序算法:
```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); // 交换当前位置和索引i处的元素
}
}
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;
}
// 测试用例
public static void main(String[] args) {
int[] arr = {9, 7, 5, 11, 12, 2, 14, 3};
int n = arr.length;
quickSort(arr, 0, n - 1);
System.out.println("Sorted array: ");
for (int num : arr) {
System.out.print(num + " ");
}
}
}
```
阅读全文
相关推荐


















