Algorithm 排序算法(堆排/快排/桶排序)

一、快速排序

private void swap(int[] a, int index1, int index2) {
        int temp = a[index1];a[index1] = a[index2];a[index2] = temp;
    }
    
    public int split(int a[],int low,int high){
        int tag = a[low]; int i= low, j = high;
        //I.方法一、从一头扫描 II.方法二、从两头扫描
        for(j=low+1; j<=high; j++){
            if(a[j] <= tag){ i = i+1; if( i != j) swap(a,i,j);}
        }
        if(i != low) swap(a,low,i);
        /*while(i < j){
            while( a[j] >= tag && i<j ) j--; 
            a[i] = a[j];
            while( a[i] <= tag && i<j ) i++; 
            a[j] = a[i];
        }
        a[i] = tag;*/
        return i;
    }
    public void  quickSort(int a[],int low,int high){
        if(low >= high) return ;//增加这两行代码可以减少递归深度
        //if(low == high-1){ if( a[low] > a[high]) swap(a,low,high); return ;}
        int mid = split(a,low,high);
        quickSort(a,low,mid-1);
        quickSort(a,mid+1,high);
    }
    
    public void quickSort(int a[]){
        Stack<Integer> stack = new Stack<Integer>();//用栈保存当前的记录
        if(a.length > 2){ stack.push(0);stack.push(a.length-1);}
        while(!stack.isEmpty()){
            int end = stack.pop(),begin = stack.pop();
            int mid = split(a,begin,end);
            if(begin < mid-1){stack.push(begin);stack.push(mid-1);}
            if(mid + 1 < end){stack.push(mid+1);stack.push(end);}
        }
    }

 

二、堆排序

public void siftUp(int a[],int n,int index){
        boolean done = false;
        if(index == 1) return ;
        while(!done && index > 1){
            if(a[index]>a[index/2]) swap(a,index,index/2);
            else done = true;
            index = index/2;
        }
    }
    public void siftDown(int a[],int n,int index){
        boolean done = false;
        if(2*index > n) return ;
        while(!done && 2*index <= n){
            index *= 2;
            if(index+1 <= n && a[index+1]>a[index]) index = index +1 ;
            if(a[index/2]<a[index]) swap(a,index/2,index);
            else done = true;
        }
    }
    public void makeHeap(int[] a,int n){
        for(int i=n/2;i>=1;i--) siftDown(a,n,i);
    }
    private void swap(int[] a, int index1, int index2) {
        int temp = a[index1];a[index1] = a[index2];a[index2] = temp;
    }
    public void heapSort(int a[]){
        makeHeap(a,a.length-1);
        for(int j=a.length-1; j>=2; j--){swap(a,1,j); siftDown(a,j-1,1);}
    }

 

三、桶排序

四、

posted @ 2016-01-03 15:44  √珞珈搬砖工√  阅读(51)  评论(0)    收藏  举报