Java快速排序的簡單算法


public class test{

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int []a={4,34,3,4545,234,43,32};
        for (int i : a) {
            System.out.print(i+" ");
        }

        System.out.println();
        int k=a.length-1;
        Sort.method(a, 0, k);
        for(int i:a){
            System.out.print(i+" ");
        }
    }

}
class Sort{
    public static void method(int source[],int low,int high){
        int i,j,x;
        if(low<high){
            i=low;
            j=high;
            x=source[i];
            //while是循環,if是判斷
            while(i<j){
                while(i<j&&source[j]>x){
                    j--;
                }
                if(i<j){
                    source[i]=source[j];
                    i++;
                }
                while(i<j&&source[i]<x){
                    i++;
                }
                if(i<j){
                    source[j]=source[i];
                    j--;
                }
            }
            //使用遞歸,i是第一個元素所確定的位置
            source[i]=x;
            method(source, low, i-1);
            method(source,i+1 , high);
            
            
        }
        
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章