排序算法之快速排序

来源:互联网 发布:淘宝不能评价 编辑:程序博客网 时间:2024/06/10 03:00

快速排序每趟排序的结果是:在选取的基准值得左边全部比其小,而右边都比其大。
下面的采用快速排序第一遍的演示:
这里写图片描述
其代码(Java)如下:

import java.util.Arrays;/** * 快速排序 *  * @author sg */public class TestQuickSort {    public static void main(String[] args) {          int a[] = { 49, 38, 65, 97, 76, 13, 27,16,32,60,49 };            quickSort(a,0,a.length-1);            System.out.println(Arrays.toString(a));    }    /**     * 快速排序      * @param src   带排序的数组     * @param low   数组的下边界     * @param high  数组的上边界     */    private static void quickSort(int[] src, int low, int high) {        //i,j分别指向待排序序列的首和尾        int i=low;        int j=high;        if(i>j)            return  ;        //每次以排序序列的首个作为比较的基准        int index=src[i];        while(i<j){            //先从右向左扫描,发现比基准小的则进行“交换”,然后换成从左边扫描            while(i<j&&src[j]>=index)                j--;            if(i<j){                src[i++]=src[j];            }            //先从左向右扫描,发现比基准大的则进行“交换”,然后换成从右边扫描            while(i<j&&src[i]<=index)                i++;            if(i<j){                src[j--]=src[i];            }           }        src[i]=index;        quickSort(src,low,i-1);        quickSort(src,i+1,high);    }}

其时间复杂度为O (nlogn),为不稳定的排序。

原创粉丝点击