快速排序

快速排序(Quicksort)是对冒泡排序的一种改进。
快速排序由C. A. R. Hoare在1962年提出。它的基本思想是:通过一趟排序将要排序的数据分割成独立的两部分,其中一部分的所有数据都比另外一部分的所有数据都要小,然后再按此方法对这两部分数据分别进行快速排序,整个排序过程可以递归进行,以此达到整个数据变成有序序列
程序:
package test;

class test
{
    public int[] sort(int[] a,int low,int high)
    {
         int l=low;
         int h=high;
         int povit=a[low];
         while(l<h)
         {
            while(l<h&&a[h]>=povit)
                  h--;
            if(l<h)
            {
                  int temp=a[h];
                  a[h]=a[l];
                  a[l]=temp;
                  l++;
            }
            while(l<h&&a[l]<=povit)
            l++;
         
                 if(l<h)
                 {
                         int temp=a[h];
                         a[h]=a[l];
                         a[l]=temp;
                         h--;
                 }
        }
        
        System.out.print("l="+(l+1)+"h="+(h+1)+"povit="+povit+"\n");
        if(l>low)sort(a,low,l-1);
        if(h<high)sort(a,l+1,high);
        return a;
    }
    
    public static void  main(String args[])
    {
        test te = new test();
        int[] a = {1,45,7,3,2,6,9,1};
        int i= 0;
        int j=a.length-1;
        te.sort(a, i, j);
        for(int m:a)
        {
            System.out.printf(" "+m);
        }
    }
}

结果:

l=1h=1povit=1
l=8h=8povit=45
l=2h=2povit=1
l=6h=6povit=7
l=5h=5povit=6
l=3h=3povit=2
l=4h=4povit=3
l=7h=7povit=9
 1 1 2 3 6 7 9 45

 

posted @ 2016-08-12 15:42  暖暖要坚持  阅读(109)  评论(0编辑  收藏  举报