首页 > 编程知识 正文

Java实现快速排序算法

时间:2023-11-20 12:58:21 阅读:308343 作者:HOMQ

本文主要阐述如何在Java中实现快速排序算法。快速排序是一种常用的排序方法,它的基本思想是:通过一趟排序将待排记录分隔成独立的两部分,其中一部分记录的关键字均比另一部分的关键字小,然后分别对这两部分继续进行排序,以达到整个序列有序。

一、快速排序算法原理

快速排序的基本思想是使用分治法。首先从数列中挑出一个元素,此处我们选择数组的首元素,称为"基准",然后调整数组元素位置,使大于基准的元素集中于一隔,小于基准的元素集中于另一区,然后再对这两个区域分别排序。基准元素选择与数组状态有关,对算法效率影响大。

public class QuickSort {
    public static void quickSort(int[] arr, int low, int high) {
        if (low < high) {
            int pivot = partition(arr, low, high);
            quickSort(arr, low, pivot - 1);
            quickSort(arr, pivot + 1, high);
        }
    }

    public static int partition(int[] arr, int low, int high) {
        int pivot = arr[low];
        while (low < high) {
            while (low < high && arr[high] >= pivot) high--;
            arr[low] = arr[high];
            while (low < high && arr[low] <= pivot) low++;
            arr[high] = arr[low];
        }
        arr[low] = pivot;
        return low;
    }
}

二、实现快速排序的细节

实现快速排序的主要难点在于如何写出partition函数以及如何处理数组的边界问题。在每次调用quickSort函数的时候,我们先通过调用partition函数,找出当前数组的划分点,然后再依次对划分点左边和右边的子数组进行排序。在partition函数中,我们首先选定一个pivot元素,然后通过比较和交换,将比pivot小的元素放到数组的左边,比pivot大的元素放到数组的右边,并在最后返回pivot的位置。

public class QuickSort {
    public static void quickSort(int[] arr, int low, int high) {
        if (low < high) {
            int pivot = partition(arr, low, high);
            quickSort(arr, low, pivot - 1);
            quickSort(arr, pivot + 1, high);
        }
    }

    public static int partition(int[] arr, int low, int high) {
        int pivot = arr[low];
        while (low < high) {
            while (low < high && arr[high] >= pivot) high--;
            arr[low] = arr[high];
            while (low < high && arr[low] <= pivot) low++;
            arr[high] = arr[low];
        }
        arr[low] = pivot;
        return low;
    }
}

三、快速排序的时间复杂度

快速排序的平均时间复杂度为O(nlogn),最好情况是当数据的最大或最小值恰好在数组中间时,时间复杂度为O(nlogn),最坏情况是当数据已经是升序或降序时,时间复杂度为O(n²)。空间复杂度为O(logn),需要注意的是,快速排序是不稳定的排序算法。

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。