排序算法六:快速排序

排序效率在同为O(N*logN)的几种排序方法中效率较高

思想: 通过一趟排序将要排序的数据分割成独立的两部分,其中一部分的所有数据都比另外一部分的所有数据都要小,然后再按此方法对这两部分数据分别进行快速排序,整个排序过程可以递归进行,以此达到整个数据变成有序序列。

在这里插入图片描述
平均时间复杂度: nlog2n ,空间复杂度: log2n,不稳定

public class QuickSort {
    /**
     * 快速排序
     * @param arr:数组名
     * @param leftbound:数组的起始下标
     * @param rightbound:数组的结束下标
     */
    public void sort(int[] arr, int leftbound, int rightbound) {
        if (leftbound >= rightbound)  return;
      int mid=partition(arr,leftbound,rightbound);           //轴的位置
      sort(arr,leftbound,mid-1);              //对轴前面的数进行快排
      sort(arr,mid+1,rightbound);              //对轴后面的数进行快排
    }

    /**
     * 将数与轴的位置的数进行大小比较,小的数在轴的前面,大的数在轴的后面
     * 左、右指针分别往中间收缩,与轴比较大小,小的放左边,大的放右边
     * @param arr:数组名
     * @param leftBound:数组的起始下标
     * @param rightBound:数组的结束下标
     * @return:返回轴的位置
     */
    public int partition(int[] arr,int leftBound,int rightBound){
        int left=leftBound;                 //数组的左边界
        int right=rightBound-1;             //轴的前面一个数
        int pivot=arr[rightBound];          //轴(最右边的数)
        while (left<=right){                //如果左指针没有越过右指针
            while (left<=right && arr[left]<=pivot)  left++;         //若小于轴,左指针往后移;循环结束后,left指针刚好指到大于轴的数的位置
            while (left<=right && arr[right]>=pivot)  right--;       //若大于轴,右指针往前移;循环结束后,right指针刚好指到小于轴的数的位置
            if (left<right){                //交换left与right指针对应的数
                int temp=arr[left];
                arr[left]=arr[right];
                arr[right]=temp;
            }
        }
        int temp=arr[left];         //将轴位置上的数插入到正确的位置
        arr[left]=arr[rightBound];
        arr[rightBound]=temp;
        return left;
    }
}


主方法:

public static void main(String[] args) {
        int[] arr={4345,245,768,4,342,23,568,923,65};
        QuickSort quickSort=new QuickSort();
        quickSort.sort(arr,0,arr.length-1);
        for (int i=0;i<arr.length;i++){
            System.out.print(arr[i]+" ");
        }
    }

输出结果:

4 23 65 245 342 568 768 923 4345

发布了18 篇原创文章 · 获赞 43 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_42194695/article/details/104565115
今日推荐