一、快速排序:

1:快速排序性能测试,随机数10000个打乱排序乱序、正序、倒序写法如下

public class QuickSort {

    //第一步
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        for(int i=0;i<10000;i++) {
            list.add(new Random().nextInt(90000));
        }
        Object[] objects = list.toArray();
        int[] arr = new int[objects.length];
        for(int i = 0; i<objects.length;i++) {
            arr[i] = (Integer) objects[i];
        }
        long time1=System.currentTimeMillis();

        quickSort(arr, 0, arr.length-1);

        long time2=System.currentTimeMillis();
        Long unSort1000000 = time2 - time1;//乱序用时毫秒
        System.out.println("乱序用时:"+unSort1000000+" ms");
        //开始正序排序
        quickSort(arr, 0, arr.length-1);
        long time3=System.currentTimeMillis();
        Long sort1000000 = time3 - time2;//正序用时秒
        System.out.println("正序用时:"+sort1000000+" ms");
        Collections.sort(list, Collections.reverseOrder());
        Object[] object1 = list.toArray();
        int[] arr1 = new int[object1.length];
        for(int i = 0; i<object1.length;i++) {
            arr1[i] = (Integer) object1[i];
        }

        long reverse1 = System.currentTimeMillis();
        quickSort(arr1, 0, arr.length-1);//倒序排序
        long reverse2 = System.currentTimeMillis();
        long reverseSort = reverse2 - reverse1;
        System.out.println("倒序排列:" +reverseSort +" ms");

    }

    public static void quickSort(int[] arr,int start ,int end) {
        if(start<end) {//有元素再排序
            //选择数组中的第零个数字做为标准数
            int base = arr[start];
            //记录需要排序第下标
            int low = start;//开始位置
            int high = end;//结束位置
            //需要循环去找数字比标准数大的,和小的数替换
            while (low < high) {
                //右边比标准数大
                while (low < high && base <= arr[high]) {
                    high--;//内移动下标,数字不需要替换
                }
                //使用右边数字替换左边数字
                arr[low] = arr[high];
                //如果左边数字比标准小
                while (low < high && arr[low] <= base) {
                    low++;//
                }
                //指向同一位置
                arr[high] = arr[low];
            }
            //把标准数给低或者高的元素
            arr[low] = base;
            //处理所有比标准数小的
            quickSort(arr, start, low);
            //处理所有比标准数大的
            quickSort(arr, low + 1, end);

        }
    }
}

2:运行效果如下所示:

快速排序 归并排序 Collections.sort正序倒序乱序性能分析

 

二、归并排序:

1:归并排序性能测试,随机数10000个打乱排序乱序、正序、倒序写法如下

public class MergerSort {

    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        for(int i=0;i<10000;i++) {
            list.add(new Random().nextInt(1000000));
        }
        Object[] objects = list.toArray();
        int[] arr = new int[objects.length];
        for(int i = 0; i<objects.length;i++) {
            arr[i] = (Integer) objects[i];
        }
        long time1=System.currentTimeMillis();

        mergeSort(arr, 0, arr.length-1);

        long time2=System.currentTimeMillis();

        Long unSort1000000 = time2 - time1;
        System.out.println("乱序排序" + unSort1000000 + "ms");
        mergeSort(arr, 0, arr.length-1);
        long time3 = System.currentTimeMillis();
        Long sort1000000 = time3 - time2;
        System.out.println("正序排序" + sort1000000 + "ms");

        Collections.sort(list, Collections.reverseOrder());
        Object[] object1 = list.toArray();
        int[] arr1 = new int[object1.length];
        for(int i = 0; i<object1.length;i++) {
            arr1[i] = (Integer) object1[i];
        }

        long reverse1 = System.currentTimeMillis();
        mergeSort(arr1, 0, arr.length-1);
        long reverse2 = System.currentTimeMillis();
        long reverseSort = reverse2 - reverse1;
        System.out.println("倒序排列:" +reverseSort +" ms");
    }

    public static void merge(int[] arr, int low, int mid, int high) {
        int[] temp = new int[high-low +1];
        int i = low;
        int j = mid+1;
        int index = 0;

        while (i<=mid&&j<=high) {
            if(arr[i] <=arr[j]) {
                temp[index] = arr[i];
                i++;
                index++;
            }else {
                temp[index] = arr[j];
                j++;
                index++;
            }
        }
        while (i<=mid) {
            temp[index] = arr[i];
            i++;
            index++;
        }
        while (j<=high) {
            temp[index] = arr[j];
            j++;
            index++;
        }

        for(int k= 0;k<temp.length;k++) {
            arr[low+k] = temp[k];
        }

    }

    public static void mergeSort(int[] arr, int low ,int high) {
        if(low<high) {
//            int mid = (high-low) << 1 + low;
            int mid = (high+low)/2;
            mergeSort(arr,low,mid);
            mergeSort(arr,mid+1, high);
            merge(arr,low,mid,high);
        }
    }
}

2:运行效果如下所示:快速排序 归并排序 Collections.sort正序倒序乱序性能分析

三、Collections.sort排序:

1:Collections.sort排序性能测试,随机数10000个打乱排序乱序、正序、倒序写法如下

public class CollectionSort {

    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        for(int i=0;i<10000;i++) {
            list.add(new Random().nextInt(90000));
        }
        Object[] objects = list.toArray();
        int[] arr = new int[objects.length];
        for(int i = 0; i<objects.length;i++) {
            arr[i] = (Integer) objects[i];
        }
        long time1 = System.currentTimeMillis();
        Collections.sort(list);
        long time2=System.currentTimeMillis();
        Long unSort1000000 = time2 - time1;//乱序用时毫秒
        System.out.println("乱序用时:"+unSort1000000+" ms");

        Collections.sort(list);

        long time3=System.currentTimeMillis();
        Long sort1000000 = time3 - time2;//正序用时秒
        System.out.println("正序用时:"+sort1000000+" ms");

        Collections.sort(list, Collections.reverseOrder());
        Object[] object1 = list.toArray();
        int[] arr1 = new int[object1.length];
        for(int i = 0; i<object1.length;i++) {
            arr1[i] = (Integer) object1[i];
        }

        long reverse1 = System.currentTimeMillis();
        Collections.sort(list);
        long reverse2 = System.currentTimeMillis();
        long reverseSort = reverse2 - reverse1;
        System.out.println("倒序排列:" +reverseSort +" ms");
    }
}

2:运行效果如下所示:快速排序 归并排序 Collections.sort正序倒序乱序性能分析

 

四、速度对比:经过多次运行,结果比例均大至稳定(本文只截取某一次结果进行讲解)

  乱序 正序 倒序
快速排序 2ms 29ms 24ms
归并排序 7ms 5ms 1ms
CollectionSort 14ms 1ms 1ms

 

 

 

 

 

五、实验过程中遇到的问题,快速排序一定是最快的么?不一定,乱序时候比较快,其他时候就比较慢了,而且快排极不稳定,在递归调用太深的情况下它会报溢出的错误。感兴趣可以把10000变大一些。Collections.sort中采用的核心算法是TimSort.sort

快速排序 归并排序 Collections.sort正序倒序乱序性能分析

它是增强型的归并排序法,性能对比归并要强大一些。保证此排序是稳定的(不会因调用 sort 方法而对相等的元素进行重新排序。这一点快排就满足不了。)

六、timSort.sort源码分析

1、源码:

Collections.sort(list); ->ArrayList.sort()->Arrays.sort((E[]) elementData, 0, size, c);->TimSort.sort(a, fromIndex, toIndex, c, null, 0, 0);->countRunAndMakeAscending(a, lo, hi, c);->binarySort(a, lo, hi, lo + initRunLen, c);
/**当LegacyMergeSort.userRequested为true的情况下,采用legacyMergeSort,否则采用TimSort.sort。并且在**legacyMergeSort的注释上标明了该方法会在以后的jdk版本中废弃,1.8中LegacyMergeSort.userRequested默认为false
**/
public static <T> void sort(T[] a, int fromIndex, int toIndex,
                            Comparator<? super T> c) {
    if (c == null) {
        sort(a, fromIndex, toIndex);
    } else {
        rangeCheck(a.length, fromIndex, toIndex);
        if (LegacyMergeSort.userRequested)
            legacyMergeSort(a, fromIndex, toIndex, c);
        else
            TimSort.sort(a, fromIndex, toIndex, c, null, 0, 0);
    }
}
/*
 * The next method (package private and static) constitutes the
 * entire API of this class.
 */

/**
 * Sorts the given range, using the given workspace array slice
 * for temp storage when possible. This method is designed to be
 * invoked from public methods (in class Arrays) after performing
 * any necessary array bounds checks and expanding parameters into
 * the required forms.
 *
 * @param a the array to be sorted
 * @param lo the index of the first element, inclusive, to be sorted
 * @param hi the index of the last element, exclusive, to be sorted
 * @param c the comparator to use
 * @param work a workspace array (slice)
 * @param workBase origin of usable space in work array
 * @param workLen usable size of work array
 * @since 1.8
 */
static <T> void sort(T[] a, int lo, int hi, Comparator<? super T> c,
                     T[] work, int workBase, int workLen) {
    assert c != null && a != null && lo >= 0 && lo <= hi && hi <= a.length;

    int nRemaining  = hi - lo;//要排序的数量
    if (nRemaining < 2)//小于二说明已经有序了
        return;  // Arrays of size 0 and 1 are always sorted

    // If array is small, do a "mini-TimSort" with no merges
    //长度小于32,则调用 binarySort,这是一个不包含合并操作的mini-TimSort排序方式
    if (nRemaining < MIN_MERGE) {//MIN_MERGE 默认值为32,
        int initRunLen = countRunAndMakeAscending(a, lo, hi, c);
        binarySort(a, lo, hi, lo + initRunLen, c);
        return;
    }

    /**
     * March over the array once, left to right, finding natural runs,
     * extending short natural runs to minRun elements, and merging runs
     * to maintain stack invariant.
     */
    TimSort<T> ts = new TimSort<>(a, c, work, workBase, workLen);
    int minRun = minRunLength(nRemaining);
    do {
        // Identify next run
        int runLen = countRunAndMakeAscending(a, lo, hi, c);

        // If run is short, extend to min(minRun, nRemaining)
        if (runLen < minRun) {
            int force = nRemaining <= minRun ? nRemaining : minRun;
            binarySort(a, lo, lo + force, lo + runLen, c);
            runLen = force;
        }

        // Push run onto pending-run stack, and maybe merge
        ts.pushRun(lo, runLen);
        ts.mergeCollapse();

        // Advance to find next run
        lo += runLen;
        nRemaining -= runLen;
    } while (nRemaining != 0);

    // Merge all remaining runs to complete sort
    assert lo == hi;
    ts.mergeForceCollapse();
    assert ts.stackSize == 1;
}

 

未完待续。。。。困了

相关文章: