首页 > 编程语言 > 详细

为什么我写的快速排序比冒泡排序慢?

时间:2015-09-27 06:34:49      阅读:447      评论:0      收藏:0      [点我收藏+]
//快速排序
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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!