java 快速排序

快速排序比插入排序快了两个数量级

package test.sort;

public class Paixu {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[] a = random(10000000);
        
        int[] b = a.clone();
        long l1 = System.currentTimeMillis();
        insert_Sort(b);
        long l2 = System.currentTimeMillis();
        System.out.println("插入排序用时:"+(l2-l1));
        check(b);
        
        
        int[] c = a.clone();
        int start = 0;
        int end = a.length-1;
        long startT = System.currentTimeMillis();
        quick_sort(c,start,end);
        long endT = System.currentTimeMillis();
        System.out.println("快速排序用时:"+(endT-startT));
        check(c);
        
    }
    // 插入排序
    private static int[] insert_Sort(int[] a){
        // 优化插入排序算法
        for(int i=1;i<a.length;i++){
            int temp=a[i];
            int j;
            // 假设 i 之前的都是有序的,i之后是无序的;
            for(j=i-1;j>=0;j--) {
                // 当前的 a[j] 比 a[i] 大,将 a[j]向后移动
                if(a[j]>temp) {
                    a[j+1]=a[j];
                }else {
                // 当前的 a[i] 比i之前的元素都大
                    break;
                }
            }
            a[j+1]=temp;
        }
        System.out.println("***********************");
        return a;
    }
    
    private static void quick_sort(int[] a,int low,int high){
        int start = low;
        int end = high;
        int key = a[low];
        
        
        while(end>start){
            //从后往前比较
            while(end>start&&a[end]>=key)  //如果没有比关键值小的,比较下一个,直到有比关键值小的交换位置,然后又从前往后比较
                end--;
            if(a[end]<=key){
                int temp = a[end];
                a[end] = a[start];
                a[start] = temp;
            }
            //从前往后比较
            while(end>start&&a[start]<=key)//如果没有比关键值大的,比较下一个,直到有比关键值大的交换位置
               start++;
            if(a[start]>=key){
                int temp = a[start];
                a[start] = a[end];
                a[end] = temp;
            }
        //此时第一次循环比较结束,关键值的位置已经确定了。左边的值都比关键值小,右边的值都比关键值大,但是两边的顺序还有可能是不一样的,进行下面的递归调用
        }
        //递归
        if(start>low) quick_sort(a,low,start-1);//左边序列。第一个索引位置到关键值索引-1
        if(end<high) quick_sort(a,end+1,high);//右边序列。从关键值索引+1到最后一个
    }
    
  // 产生随机数组
public static int[] random(int num) { long start = System.currentTimeMillis(); int[] a ; a = new int[num]; for (int i = 0; i < num; i++) { int rand = (int) Math.round(Math.random()*num*100000); a[i] = rand; } long end =System.currentTimeMillis(); System.out.println("产生"+num+"个随机数花费时间=====>"+(end-start)+"毫秒"); return a; }
  // 检验排序结果
private static void check (int[] a) { boolean flag = true; for (int i = 0; i < a.length-1; i++) { if (a[i+1] < a[i]) { flag = false; break; } } System.out.println(flag?"排序成功":"排序失败"); } }
原文地址:https://www.cnblogs.com/zhengwenqiang/p/7798309.html