快速排序 (Quick Sort)
快速排序是一种高效的排序算法,采用分治法策略。它的基本思想是:
- 从数列中挑出一个元素作为"基准"(pivot)
- 重新排序数列,所有比基准值小的元素放在基准前面,比基准值大的元素放在基准后面(相同的数可以到任一边)。这个操作称为分区(partition)
- 递归地对小于基准值的子数列和大于基准值的子数列进行排序
时间复杂度
- 平均情况:O(n log n)
- 最坏情况:O(n^2)(当数组已经排序或所有元素相同时)
- 最好情况:O(n log n)
Java实现
public class QuickSort {
public static void quickSort(int[] arr) {
if (arr == null || arr.length == 0) {
return;
}
quickSort(arr, 0, arr.length - 1);
}
private static void quickSort(int[] arr, int low, int high) {
if (low < high) {
// 找到分区点
int partitionIndex = partition(arr, low, high);
// 递归排序左子数组
quickSort(arr, low, partitionIndex - 1);
// 递归排序右子数组
quickSort(arr, partitionIndex + 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++;
// 交换arr[i]和arr[j]
swap(arr, i, j);
}
}
// 将基准放到正确的位置
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 = {10, 7, 8, 9, 1, 5};
System.out.println("排序前:");
for (int num : arr) {
System.out.print(num + " ");
}
quickSort(arr);
System.out.println("\n排序后:");
for (int num : arr) {
System.out.print(num + " ");
}
}
}代码说明
- quickSort(int[] arr) 是公共方法,用于启动排序过程
- quickSort(int[] arr, int low, int high) 是递归方法,实现分治策略
- partition(int[] arr, int low, int high) 方法实现分区操作:
- 选择最右边的元素作为基准(pivot)
- 将所有小于pivot的元素移到左边
- 将所有大于pivot的元素移到右边
- 最后将pivot放到正确的位置
- swap 方法用于交换数组中的两个元素
快速排序是一种原地排序算法(不需要额外的存储空间),但在最坏情况下性能会下降。在实际应用中,通常会结合插入排序等简单算法来优化小数组的排序。
