快速排序

来源:互联网 发布:淘宝固定悬浮导航 编辑:程序博客网 时间:2024/06/16 01:45

快速排序

在所有的排序算法中,快速排序算是很不错的了。实现起来简单,而且它的平均复杂度为O(nlogn)。性能相对于冒泡,选择和插入要好很多了。

由于近几天回顾了一下数据结构的知识,温顾而知新(@_@)。所以用java实现了一遍。代码如下:

package Qsort;public class Qsort {    //找标准值    public static int pivotloc(int arr[],int left, int right){        int pivot = arr[left];        while(left < right){            //如果右边比pivot大,则右边下标左移一位            while(left < right && arr[right] > pivot)                right--;            //如果右边值比pivot小,则把右边下标的值赋值给左边的值            //,也许会有疑惑,因为左边下标的值此时会被覆盖掉了,            //但是,它还保存在pivot中,并没有丢失。同时左边下标右移动一位            if(left < right){                arr[left] = arr[right];                left++;            }            while(left < right && arr[left] < pivot)                left++;            if(left < right){                arr[right] = arr[left];                right--;            }        }        arr[left] = pivot;        return left;    }    //快排    public static int[] qsort(int a[],int left, int right){        if(left < right){            //找出标准值            int pivotIndex = pivotloc(a,left, right);            qsort(a, left, pivotIndex-1);            qsort(a, pivotIndex+1, right);        }        return a;    }    public static void main(String[] args) {        int a[] = {1,12,6,15,12,31,4};        //返回已排好序的数组        a = qsort(a,0, a.length-1);        for(int i = 0; i < a.length; i++)            System.out.println(a[i]);    }}

参考书籍《数据结构–Java语言描述》刘小晶版。

1 0
原创粉丝点击