基于java的快速排序

      因为上次面试师兄让我上机写个快排的算法,我没有写出来,很尴尬,今天把快排实现了一遍,以后遇到就不会掉这个坑了。

package testt;

public class fastsort {
   public  static void main(String [] args){
       int []a={4,2,56,26,38,12};
       int start=0;
       int end=a.length-1;
       sort(a,start,end);
       for (int i=0;i<a.length;i++)
       {
           System.out.println(a[i]);
       }
   }
   public static void sort(int []a,int low,int heigh){
       int start=low;
       int end=heigh;
       int key=a[low];
       while (end>start){
           while ((end>start)&&(a[end]>key))//从右向左遍历
               end--;
           if((end>start)&&(a[end]<=key)){
               //说明从右向左遍历找到了一个值比key值要小,所以进行交换
               int temp=a[end];
               a[end]=a[start];
               a[start]=temp;
           }
           //接着从左向右遍历
           while ((end>start)&&(a[start]<key))
                  start++;
           //找到了一个比key值要大的所以进行交换
           if((end>start)&&(a[start]>=key)){
               int temp=a[start];
               a[start]=a[end];
               a[end]=temp;
           }
       }
       //这样一个循环过来就第一次排序完成,接着进行递归
       if (low<start)
           //进行左递归
           sort(a,low,start-1);
       if (end<heigh)
           //进行右递归
           sort(a,end+1,heigh);
   }

}

猜你喜欢

转载自blog.csdn.net/weixin_40593587/article/details/81005593