网站首页 网站地图
网站首页 > 创业资讯 > java快速排序

java快速排序

时间:2026-03-25 05:09:36

快速排序是一种高效的排序算法,采用分治法策略。其基本思想是:

选择基准值:

从数组中选择一个元素作为基准值(pivot)。通常可以选择数组的第一个元素、最后一个元素或中间元素,也可以随机选择。

分区操作:

重新排列数组,使得所有比基准值小的元素放在基准值的左边,所有比基准值大的元素放在基准值的右边。在这个过程结束时,基准值就处于数组的最终位置。

递归排序:

对基准值左边和右边的两个子数组分别递归地执行快速排序。

```java

public class QuickSort {

public static void quickSort(int[] array, int low, int high) {

if (low < high) {

// 获取分区点

int pivotIndex = partition(array, low, high);

// 对左子数组排序

quickSort(array, low, pivotIndex - 1);

// 对右子数组排序

quickSort(array, pivotIndex + 1, high);

}

}

private static int partition(int[] array, int low, int high) {

// 选择最后一个元素作为基准值

int pivot = array[high];

int i = low - 1;

for (int j = low; j < high; j++) {

if (array[j] <= pivot) {

i++;

// 交换元素

swap(array, i, j);

}

}

// 将基准值放到正确的位置

swap(array, i + 1, high);

return i + 1;

}

private static void swap(int[] array, int i, int j) {

int temp = array[i];

array[i] = array[j];

array[j] = temp;

}

public static void main(String[] args) {

int[] array = {38, 27, 43, 3, 9, 82, 10};

System.out.println("原始数组: " + Arrays.toString(array));

quickSort(array, 0, array.length - 1);

System.out.println("排序后的数组: " + Arrays.toString(array));

}

}

```

关键点解释:

基准值的选择:

基准值的选择对算法的效率有很大影响。通常选择数组的最后一个元素作为基准值,但也可以选择第一个元素、中间元素或随机选择。

分区操作:

分区操作是快速排序的核心。通过遍历数组,将小于基准值的元素移到左边,大于基准值的元素移到右边。

递归排序:

对基准值左右两边的子数组分别递归调用快速排序,直到每个子数组只有一个元素或没有元素。

时间复杂度:

平均时间复杂度:O(n log n)

最坏时间复杂度:O(n²)(当每次选择的基准值总是最大或最小值时)

空间复杂度:

O(log n)(递归栈的深度)

快速排序是一种原地排序算法,不需要额外的存储空间,适合大规模数据排序。