快速排序

来源:互联网 发布:java redis缓存数据库 编辑:程序博客网 时间:2024/06/13 21:23

本文章转自:http://blog.csdn.net/wangkuifeng0118/article/details/7286332
快速排序的基本思想:

     通过一趟排序将待排序记录分割成独立的两部分,其中一部分记录的关键字均比另一部分关键字小,则分别对这两部分继续进行排序,直到整个序列有序。     把整个序列看做一个数组,把第零个位置看做中轴,和最后一个比,如果比它小交换,比它大不做任何处理;交换了以后再和小的那端比,比它小不交换,比他大交换。这样循环往复,一趟排序完成,左边就是比中轴小的,右边就是比中轴大的,然后再用分治法,分别对这两个独立的数组进行排序。

这里写图片描述

public class Quicksort{    public static int getmiddle(int[] A, int low, int high){        int mid = A[low];//数组的第一个作为中轴        while(low < high) {            while(low < high && A[high] <= mid) {                  high--;            }            A[low] = A[high];//比中轴小的记录移到低端            while(low < high && A[low] >= mid) {                low++;            }            A[high] = A[low];//比中轴大的记录移到高端        }        A[low] = mid;        return low;    }    //递归形式的分治排序算法    public static void _quicksort(int[] A, int low, int high){        if(low < high) {            int mid = getmiddle(A, low, high);            _quicksort(A, low, mid - 1);            _quicksort(A, mid + 1, high);        }    }    public static void main(String[] args)    {        int[] A = {49, 38, 65, 97, 76, 13, 27, 49};        _quicksort(A, 0, A.length - 1);        for(int i = 0; i < A.length; i++) {            System.out.println(A[i]);        }    }}

Result:
97
76
65
49
49
38
27
13

快速排序是对冒泡排序的一种改进,平均时间复杂度是O(nlogn)。

0 0
原创粉丝点击