一些大学学过的基础在这里总结一下

package base.sort;

import java.util.Arrays;
import java.util.Random;
//O(nlogn) 快速排序
public class QuickSort {

    public static void main(String[] args) {
        
        QuickSort sort = new QuickSort();
        int[] a = new int[32];
        Random rand = new Random();
        for (int i = 0; i < a.length; i++) {
            a[i] = (int) (rand.nextLong()%100); 
        }
        System.out.println("start Array: " + Arrays.toString(a));
        sort.sort(a,0,a.length);
        System.out.println("result Array: " + Arrays.toString(a));
    }
    
    public void sort(int[] a,int m,int n){
        
        if(m != n){
            int i = partition(a,m,n);
            sort(a,m,i);
            sort(a,i+1,n);
        }
    }
    
    public int partition(int[] a,int m,int n){
        
        int x = a[m];
        int i = m;
        
        for(int j=i+1;j<n;j++){
            if(a[j]<=x){
                i = i+1;
                exchange(a,i,j);
            }
        }
        exchange(a,m,i);
        return i;
    }
    
    public void exchange(int[] a,int i,int j){
        int temp = 0;
        temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }
}

 

posted on 2012-04-22 13:08  真心的不懂  阅读(214)  评论(0编辑  收藏  举报