快排算法的实现

来源:互联网 发布:rar怎么解压到mac 编辑:程序博客网 时间:2024/04/24 22:08

快排算法的实现

自己按照书上的想法实现了快排,代码可用但是不够优雅。
先说一下我的总体思路(递归实现):

  1. 默认数组的第一个作为快排的中轴;
  2. 通过quicksort求出中轴在一次快排之后的位置,作为分裂点;
  3. 分别再对分裂点两侧进行快排;

求中轴的位置():

  1. 保存第一个数作为中轴,并保护起来;
  2. j从右边开始向左,直到遇到比中轴小的停下来;
  3. 覆盖左边的i指向的数交换(因为第一个一定是中轴,而已经被保护起来了,保存在别的变量里,所以不慌);
  4. i开始移动,找到比中轴大的数停止;
  5. i指向的数覆盖j指向的数;
  6. 直到i和j相遇,把中轴覆盖这个数;

这个比较恶心的是没有用正常人的交换而是覆盖,因为一开始就把中轴保护起来了,所以覆盖就无所谓,一旦覆盖就有两个数了,所以再覆盖也没关系,以此类推。

package alo;import myUtil.Arr;import myUtil.MyRandom;/** *  * @author liuxiaoxiong * */public class QuickSort {    public static void main(String[] args) {        // TODO Auto-generated method stub        int a[] = MyRandom.randArr(100, -50, 100);        // int a[]={28, 30, 71, 36};//This is the test data.        Arr.printArr(a);        qSort(a, 0, a.length - 1);        Arr.printArr(a);    }    public static void qSort(int arr[], int begin, int end) {        if (begin == end) {            return;        }        int ax = quickSort(arr, begin, end);        /**         * It's IMPORTANT or it will out of bound when ax=begin or end if your         * para next is qSort(<para>arr</para>,<para>begin</para>,         * <para>ax</para>-1) or qSort(<para>arr</para>,<para>ax</para>+1,         * <para>end<para>).On the other hand,if you do not +1 ro -1,then it         * can't stop until stack overflow.         */        if (ax > begin) {            qSort(arr, begin, ax-1 );        }        if (ax < end) {            qSort(arr, ax+1, end);        }//      if (ax != begin && ax != end) {//          qSort(arr, ax+1, end);//          qSort(arr, begin, ax-1);//      }    }    /**     *      * @param arr     *            the array unorderd.     * @param begin     *            the begin of the array.     * @param end     * @return Actuually,it return the position of the partition.At the left of     *         the partition     */    public static int quickSort(int arr[], int begin, int end) {        if (begin == end)            return begin;        int aix = arr[begin];        // the flag if the point i or j should move.        // Maybe the best thing I picked in my brain.haha.        boolean imove = false;        int i = begin;        int j = end;        while (true) {            if (i == j) {                arr[i] = aix;                System.out.println(i);                return i;            }            // move the right point            if (arr[j] < aix && (!imove)) {                arr[i] = arr[j];                imove = true;            }            // move the left point            if (arr[i] > aix && imove) {                arr[j] = arr[i];                imove = false;            }            // which point should move            if (imove)i++; else j--;        }    }}

可以说明一下的是我自己实现了一个简单的工具类,Arr和MyRandom,都是非常简单的。

其中MyRandom:

package myUtil;public class MyRandom {    /**     * create a array that is integer     * @param num the number of random integer     * @param min the mininum number in the array     * @param max the maxium number in the array     * @return the array of random integer     */    public static int[] randArr(int num,int min,int max){        int []randArr=new int [num];        while(num--!=0){            randArr[num]=(int) (Math.random()*(max-min+1))+min;//        }        return randArr;    }    /**     *      * @param num the length of array     * @return the array of random double      */    public static double[] randArr(int num){        double randArr[]=new double [num];        while(num--!=0){            randArr[num]=Math.random();        }        return randArr;    }}

总的来说我想把所有的和随机有关的都集中在这个工具类实现。

Arr:

package myUtil;import java.util.Arrays;public class Arr {    public static String printArr(int a[]){        String str=Arrays.toString(a);        System.out.println(str);        return str;    }}

简单地输出数组的所有内容,尽管有很多实现方法,不过这样总是简单多了,能省则省。

//print the arrays like this.for(int a:aa){    System.out.print(a+" ");}

但是我又和网上的一些代码对比了一下:

原作者地址

package alo;import myUtil.MyRandom;/** * the QuickSort from Internet * @author http://www.cnblogs.com/wouldguan/archive/2013/02/20/2918191.html * much better than mine */public class Hello {    /**     *      * @param data      * @param low      * @param hight      */    private static void quickSort(int data[], int low, int hight) {        int i = low, j = hight;        //Take the center of arrays as the axi,so that we can skip the part to calculate.        int mid = data[(low + hight) / 2];        //        while (i <= j) {            //the i point go right until it it meet the number >=it.            while (data[i] < mid)                i++;            while (data[j] > mid)                j--;            if (i <= j) {                int temp = data[i];                data[i] = data[j];                data[j] = temp;                i++;                j--;            }        }        if (i < hight)            quickSort(data, i, hight);        if (j > low)            quickSort(data, low, j);    }    public static void main(String[] args) {        int[] data = MyRandom.randArr(15, -50, 100);        quickSort(data, 0, data.length - 1);        for (int n : data) {            System.out.print(n + " ");        }    }}

比我的优雅多了。
很容易理解。

0 0
原创粉丝点击