//快速排序
public class QuickSort {
    public static void quickSort(int[] a,int low,int high){
        int mid;
        int ltemp,rtemp;
        ltemp=low;rtemp=high;
        mid=a[(low+high)>>>1];
        while(ltemp<rtemp){//把比mid小的放在左侧,比mid大的放在右侧
            while(a[ltemp]<mid){
                ltemp++;
            }
            while(a[rtemp]>mid){
                rtemp--;
            }
            if(ltemp<rtemp){//交换
                a[ltemp]=a[ltemp]^a[rtemp];
                a[rtemp]=a[ltemp]^a[rtemp];
                a[ltemp]=a[ltemp]^a[rtemp];
                ltemp++;rtemp--;
            }
        }
        if(ltemp==rtemp){
            ltemp++;
        }
        if(ltemp<high) quickSort(a,ltemp,high);
        if(low<rtemp) quickSort(a,low,rtemp);
    }
}
//冒泡排序
public class Sort {
    public static void sort(int[] a){
        int j=0;
        for(int i=1;i<a.length;i++){//循环
            
            j=i-1;
            while(j>=0&&a[j+1]<a[j]){//交换
                a[j]=a[j+1]^a[j];a[j+1]=a[j+1]^a[j];a[j]=a[j+1]^a[j];//交换
                j--;
            }
        }
    }
}
//测试
class MyTimer{//计时方法。
    private final long start;
    public MyTimer(){
        start=System.currentTimeMillis();
    }
    public long getElapsed(){
        return System.currentTimeMillis()-start;
    }
}
public class Test {
    //测试方法
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        MyTimer t1=new MyTimer();
        for(int i=0;i<100;i++){//测试快速排序速度
            int[]  a = new int[1000];
            for(int j=0;j<a.length-1;j++){
                a[j]=(int) (Math.random()*100);
                QuickSort.quickSort(a,0,a.length-1);
            }
        }
        System.out.println(t1.getElapsed());
        t1=new MyTimer();
        for(int i=0;i<100;i++){//测试冒泡排序速度
            int[]  a = new int[1000];
            for(int j=0;j<a.length-1;j++){
                a[j]=(int) (Math.random()*100);
                Sort.sort(a);
            }
        }
        System.out.println(t1.getElapsed());
        t1=new MyTimer();
        for(int i=0;i<100;i++){//测试系统内快速排序速度
            int[]  a = new int[1000];
            for(int j=0;j<a.length-1;j++){
                a[j]=(int) (Math.random()*100);
                java.util.Arrays.sort(a);
            }
        }
        System.out.println(t1.getElapsed());
    }
}结果:
2150
221
730
本文出自 “java小僧” 博客,请务必保留此出处http://fly2017.blog.51cto.com/5237541/1698455
原文:http://fly2017.blog.51cto.com/5237541/1698455