快速排序-记录

ps:有一次朋友问到快速排序,嘴上说着简单没几行代码,直接写出来TMD费劲了,这次又被问了一次,又尴尬了,记录一下张张记性

原理(度娘):

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

代码(JAVA):

 

private static void QSort(int[] arr,int start,int end)
    {
        int from = start;
        int to = end;
        int key = arr[from];while(from<to)
        {
            while(to>from&&arr[to]>key)
            {
                to--;
            }
            if(to>from)
            {
                int tem = arr[from];
                arr[from] = arr[to];
                arr[to] = tem;
            }
            while(from<to&&arr[from]<key)
            {
                from++;
            }
            if (to>from) {
                int tem = arr[from];
                arr[from] = arr[to];
                arr[to] = tem;
            }
            
        }if (from>start) {
            QSort(arr, start, from-1);
        }
        if (to<end) {
            QSort(arr, to+1, end);
        }
    }

 

  

posted @ 2015-11-27 22:32  iamcler  阅读(155)  评论(0编辑  收藏  举报