arrays排序算法(代码片段)

xhBruce xhBruce     2022-12-04     750

关键词:

Arrays排序算法

import java.util.Arrays;
排序算法 - 数据结构


Arrays.sort耗时

100000 个数升序排列耗时测试:
耗时: 14、耗时: 10、耗时: 14、耗时: 11、耗时: 13、耗时: 10、耗时: 11、耗时: 12、耗时: 17、耗时: 15
从时间上查看排序算法 - 数据结构,与快速排序、堆排序、计数排序接近。

双基准快速排序

在这里插入图片描述

DualPivotQuicksort.sort

这里参数中right是数组a.length - 1
在这里插入图片描述

使用快速排序

数组小于286 使用快速排序

private static final int QUICKSORT_THRESHOLD = 286;

优先使用插入排序

数组小于47 则优先使用插入排序而不是快速排序

private static final int INSERTION_SORT_THRESHOLD = 47;

                /*
                 * Traditional (without sentinel) insertion sort,
                 * optimized for server VM, is used in case of
                 * the leftmost part.
                 */
                for (int i = left, j = i; i < right; j = ++i) 
                    int ai = a[i + 1];
                    while (ai < a[j]) 
                        a[j + 1] = a[j];
                        if (j-- == left) 
                            break;
                        
                    
                    a[j + 1] = ai;
                
Arrays.sort中快速排序
    private static void sort(int[] a, int left, int right, boolean leftmost) 
        int length = right - left + 1;

        // Use insertion sort on tiny arrays
        if (length < INSERTION_SORT_THRESHOLD) 
            if (leftmost) 
                /*
                 * Traditional (without sentinel) insertion sort,
                 * optimized for server VM, is used in case of
                 * the leftmost part.
                 */
                for (int i = left, j = i; i < right; j = ++i) 
                    int ai = a[i + 1];
                    while (ai < a[j]) 
                        a[j + 1] = a[j];
                        if (j-- == left) 
                            break;
                        
                    
                    a[j + 1] = ai;
                
             else 
                /*
                 * Skip the longest ascending sequence.
                 */
                do 
                    if (left >= right) 
                        return;
                    
                 while (a[++left] >= a[left - 1]);

                /*
                 * Every element from adjoining part plays the role
                 * of sentinel, therefore this allows us to avoid the
                 * left range check on each iteration. Moreover, we use
                 * the more optimized algorithm, so called pair insertion
                 * sort, which is faster (in the context of Quicksort)
                 * than traditional implementation of insertion sort.
                 */
                for (int k = left; ++left <= right; k = ++left) 
                    int a1 = a[k], a2 = a[left];

                    if (a1 < a2) 
                        a2 = a1; a1 = a[left];
                    
                    while (a1 < a[--k]) 
                        a[k + 2] = a[k];
                    
                    a[++k + 1] = a1;

                    while (a2 < a[--k]) 
                        a[k + 1] = a[k];
                    
                    a[k + 1] = a2;
                
                int last = a[right];

                while (last < a[--right]) 
                    a[right + 1] = a[right];
                
                a[right + 1] = last;
            
            return;
        

        // Inexpensive approximation of length / 7
        int seventh = (length >> 3) + (length >> 6) + 1;

        /*
         * Sort five evenly spaced elements around (and including) the
         * center element in the range. These elements will be used for
         * pivot selection as described below. The choice for spacing
         * these elements was empirically determined to work well on
         * a wide variety of inputs.
         */
        int e3 = (left + right) >>> 1; // The midpoint
        int e2 = e3 - seventh;
        int e1 = e2 - seventh;
        int e4 = e3 + seventh;
        int e5 = e4 + seventh;

        // Sort these elements using insertion sort
        if (a[e2] < a[e1])  int t = a[e2]; a[e2] = a[e1]; a[e1] = t; 

        if (a[e3] < a[e2])  int t = a[e3]; a[e3] = a[e2]; a[e2] = t;
            if (t < a[e1])  a[e2] = a[e1]; a[e1] = t; 
        
        if (a[e4] < a[e3])  int t = a[e4]; a[e4] = a[e3]; a[e3] = t;
            if (t < a[e2])  a[e3] = a[e2]; a[e2] = t;
                if (t < a[e1])  a[e2] = a[e1]; a[e1] = t; 
            
        
        if (a[e5] < a[e4])  int t = a[e5]; a[e5] = a[e4]; a[e4] = t;
            if (t < a[e3])  a[e4] = a[e3]; a[e3] = t;
                if (t < a[e2])  a[e3] = a[e2]; a[e2] = t;
                    if (t < a[e1])  a[e2] = a[e1]; a[e1] = t; 
                
            
        

        // Pointers
        int less  = left;  // The index of the first element of center part
        int great = right; // The index before the first element of right part

        if (a[e1] != a[e2] && a[e2] != a[e3] && a[e3] != a[e4] && a[e4] != a[e5]) 
            /*
             * Use the second and fourth of the five sorted elements as pivots.
             * These values are inexpensive approximations of the first and
             * second terciles of the array. Note that pivot1 <= pivot2.
             */
            int pivot1 = a[e2];
            int pivot2 = a[e4];

            /*
             * The first and the last elements to be sorted are moved to the
             * locations formerly occupied by the pivots. When partitioning
             * is complete, the pivots are swapped back into their final
             * positions, and excluded from subsequent sorting.
             */
            a[e2] = a[left];
            a[e4] = a[right];

            /*
             * Skip elements, which are less or greater than pivot values.
             */
            while (a[++less] < pivot1);
            while (a[--great] > pivot2);

            /*
             * Partitioning:
             *
             *   left part           center part                   right part
             * +--------------------------------------------------------------+
             * |  < pivot1  |  pivot1 <= && <= pivot2  |    ?    |  > pivot2  |
             * +--------------------------------------------------------------+
             *               ^                          ^       ^
             *               |                          |       |
             *              less                        k     great
             *
             * Invariants:
             *
             *              all in (left, less)   < pivot1
             *    pivot1 <= all in [less, k)     <= pivot2
             *              all in (great, right) > pivot2
             *
             * Pointer k is the first index of ?-part.
             */
            outer:
            for (int k = less - 1; ++k <= great; ) 
                int ak = a[k];
                if (ak < pivot1)  // Move a[k] to left part
                    a[k] = a[less];
                    /*
                     * Here and below we use "a[i] = b; i++;" instead
                     * of "a[i++] = b;" due to performance issue.
                     */
                    a[less] = ak;
                    ++less;
                 else if (ak > pivot2)  // Move a[k] to right part
                    while (a[great] > pivot2) 
                        if (great-- == k) 
                            break outer;
                        
                    
                    if (a[great] < pivot1)  // a[great] <= pivot2
                        a[k] = a[less];
                        a[less] = a[great];
                        ++less;
                     else  // pivot1 <= a[great] <= pivot2
                        a[k] = a[great];
                    
                    /*
                     * Here and below we use "a[i] = b; i--;" instead
                     * of "a[i--] = b;" due to performance issue.
                     */
                    a[great] = ak;
                    --great;
                
            

            // Swap pivots into their final positions
            a[left]  = a[less  - 1]; a[less  - 1] = pivot1;
            a[right] = a[great + 1]; a[great + 1] = pivot2;

            // Sort left and right parts recursively, excluding known pivots
            sort(a, left, less - 2, leftmost);
            sort(a, great + 2, right, false);

            /*
             * If center part is too large (comprises > 4/7 of the array),
             * swap internal pivot values to ends.
             */
            if (less < e1 && e5 < great) 
                /*
                 * Skip elements, which are equal to pivot values.
                 */
                while (a[less] == pivot1) 
                    ++less;
                

                while (a[great] == pivot2) 
                    --great;
                

                /*
                 * Partitioning:
                 *
                 *   left part         center part                  right part
                 * +----------------------------------------------------------+
                 * | == pivot1 |  pivot1 < && < pivot2  |    ?    | == pivot2 |
                 * +----------------------------------------------------------+
                 *              ^                        ^       ^
                 *              |                        |       |
                 *             less                      k     great
                 *
                 * Invariants:
                 *
                 *              all in (*,  less) == pivot1
                 *     pivot1 < all in [less,  k)  < pivot2
                 *              all in (great, *) == pivot2
                 *
                 * Pointer k is the first index of ?-part.
                 */
                outer:
                for (int k = less - 1; ++k <= great; ) 
                    int ak = a[k];
                    if (ak == pivot1)  // Move a[k] to left part
                        a[k] = a[less];
                        a[less] = ak;
                        ++less;
                     else if (ak == pivot2)  // Move a[k] to right part
                        while (a[great] == pivot2) 
                            if (great-- == k) 
                                break outer;
                            
                        
                        if (a[great] == pivot1)  // a[great] < pivot2
                            a[k] = a[less];
                            /*
                             * Even though a[great] equals to pivot1, the
                             * assignment a[less] = pivot1 may be incorrect,
                             * if a[great] and pivot1 are floating-point zeros
                             * of different signs. Therefore in float and
                             * double sorting methods we have to use more
                             * accurate assignment a[less] = a[great].
                             */
                            a[less] = pivot1;
                            ++less;
                         else  // pivot1 < a[great] < pivot2
                            a[k] = a[great];
                        
                        a[great] = ak;
                        --great;
                    
                
            

            // Sort center part recursively
            sort(a, less, great, false);

         else  // Partitioning with one pivot
            /*
             * Use the third of the five sorted elements as pivot.
             * This value is inexpensive approximation of the median.
             */
            int pivot = a[e3];

            /*
             * Partitioning degenerates to the traditional 3-way
             * (or "Dutch National Flag") schema:
             *
             *   left part    center part              right part
             * +-------------------------------------------------+
             * |  < pivot  |   == pivot   |     ?    |  > pivot  |
             * +-------------------------------------------------+
             *              ^              ^        ^
             *              |              |        |
             *             less            k      great
             *
             * Invariants:
             *
             *   all in (left, less)   < pivot
             *   all in [less, k)     == pivot
             *   all in (great, right) > pivot
             *
             * Pointer k is the first index of ?-part.
             */
            for (int k = less; k <= great; ++k) 
                if (a[k] == pivot) 
                    continue;
                
                int ak = a[k];
                if (ak < pivot)  // Move a[k] to left part
                    a[k] = a[less];
                    a[less] = ak;
                    ++less;
                 else  // a[k] > pivot - Move a[k] to right part
                    while (a[great] > pivot) 
                        --great;
                    
                    if (a[great] < pivot)  // a[great] <= pivot
                        a[k] = a[less];
                        a[less] = a[great];
                        ++less;
                     else  // a[great] == pivot
                        /*
                         * Even though a[great] equals to pivot, the
                         * assignment a[k] = pivot may be incorrect,
                         * if a[great] and pivot are floating-point
                         * zeros of different signs. Therefore in float
                         * and double sorting methods we have to use
                         * more accurate assignment a[k] = a[great].
                         */
                        a[k] = pivot;
                    
                    a[great] = ak;
                    --great;
                
            

            /*
             * Sort left and right parts recursively.
             * All elements from center part are equal
             * and, therefore, already sorted.
             */
            sort(a, left, less - 1, leftmost);
            sort(a, great + 1, right, false);
        
    

>QUICKSORT_THRESHOLD 情况

  • 数组不是高度结构化的,请使用快速排序而不是合并排序。
  • 使用或创建临时数组b进行合并
    static void sort(int[] a, int left, int right,
                     int[] work, int workBase, int workLen) 
        // Use Quicksort on small arrays
        if (right - left < QUICKSORT_THRESHOLD) 
            sort(a, left, right, true);
            return;
        

        /*
         * Index run[i] is the start of i-th run
         * (ascending or descending sequence).
         */
        int[] run = new int[MAX_RUN_COUNT + 1];
        int count = 0; run[0] = left;

        // Check if the array is nearly sorted
        for (int k = left; k < right; run[count] = k) 
            // Equal items in the beginning of the sequence
            while (k < right && a[k] == a[k + 1])
                k++;
            if (k == right) break;  // Sequence finishes with equal items
            if (a[k] < a[k + 1])  // ascending
                while (++k <= right && a[k - 1] <= a[k]);
             else if (a[k] > a[k + 1])  // descending
                while (++k <= right && a[k - 1] >= a[k]);
                // Transform into an ascending sequence
                for (int lo = run[count] - 1, hi = k; ++lo < --hi; ) 
                    int t = a[lo]; a[lo] = a[hi]; a[hi] = t;
                
            

            // Merge a transformed descending sequence followed by an
            // ascending sequence
            if (run[count] > left && a[run[count]查看详情  

2.1初级排序算法(代码片段)

2.1demo的C语言实现/**实现数组从小到大顺序排列*/#include<stdio.h>#include<stdlib.h>#defineless(a,b)(a<b)#defineexch(array,a,b)dointtmp=array[a];array[a]=array[b];array[b]=tmp;while(0)/**选择排序法*/voidsele 查看详情

排序算法(代码片段)

快速排序算法importjava.util.Arrays;publicclassQuickSortpublicstaticvoidmain(String[]args)int[]arr=4,5,1,9,10,5;quickSore(arr,0,arr.length-1);System.out.println(Arrays.toString(arr));publicstaticintgetI 查看详情

java实现希尔排序算法(代码片段)

希尔排序就是对直接插入排序的一个优化。见代码:packagecom.steven;publicclassShellSort /***希尔排序*@paramarrays需要排序的序列*/publicstaticvoidsort(int[]arrays)if(arrays==null||arrays.length<=1)return;//增量intincrementNum=arrays.length... 查看详情

排序算法之插入排序(代码片段)

...oidmain(String[]args)int[]arrays=3,9,63,93,72,15,27,86;System.out.println("排序前的数据为:");display(arrays);doInsertSort(arrays);System.out.println("排序后的数据为:") 查看详情

java实现希尔排序算法(代码片段)

希尔排序就是对直接插入排序的一个优化。见代码:packagecom.steven;publicclassShellSort /***希尔排序*@paramarrays需要排序的序列*/publicstaticvoidsort(int[]arrays)if(arrays==null||arrays.length<=1)return;//增量int 查看详情

排序算法之冒泡排序(代码片段)

前言排序算法中最最常见也算是入门的一个排序算法就是冒泡排序。这篇文章我们就来好好地写写这个冒泡排序算法,以及冒泡排序呢的改进算法。传统冒泡算法staticint[]array=100,1,5,4,11,2,20,18,89,34,20,34;@TestpublicvoidbubbleSortNormal()intt... 查看详情

排序算法-归并算法(代码片段)

在实际应用当中,对于数据较大的输入,归并排序是比较快的一个算法。该算法采用的是分治法的思想。原理:将数据分开排序,然后进行合并,最后形成一个排好的序列。将其合并输出,如下图所示:代码实现如下:/***归并... 查看详情

排序算法之希尔排序(代码片段)

一、原理?希尔排序是直接插入排序的一种更高效的改进版本。它把记录按下标的一定增量进行分组,然后对每组使用直接插入排序;随着增量逐渐减少每组中包含的元素越来越多,也越来越有序,当增量减到为1时,整个序列就... 查看详情

排序算法之堆排序(代码片段)

一、原理?堆排序是采用数据结构堆进行排序的算法。堆是一种近似完全二叉树的结构,并同时满足堆的性质:子节点的键值或索引总是小于(或大于)它的父节点。?堆中定义以下几种操作:?1)最大堆调整(MaxHeapify):将堆的末端子节点... 查看详情

排序算法(代码片段)

java实现快速排序、插入排序、选择排序1packagecom.java;2importjava.util.Arrays;34publicclassSort5publicstaticvoidmain(String[]args)6int[]array=15,5,3,9,4,82,35,45,7,11;7System.out.print("排序前的数组:");8System.out.print 查看详情

算法——希尔排序与快速排序(代码片段)

ArrayList.prototype.shellSort=function()letlength=this.array.lengthletgap=Math.floor(length/2)while(gap>=1)for(leti=gap;i<length;i++)lettemp=this.array[i]letj=i;while(temp<this.array[j-gap 查看详情

希尔排序(代码片段)

Brief希尔排序是希尔(DonaldShell)于1959年提出的一种排序算法,是一种插入排序,是简单插入排序经过改进之后的一个更高效的版本,也称为缩小增量排序,同时该算法是冲破O(n^2)的第一批算法之一//插入排序,升序publicstaticvoidi... 查看详情

排序算法的简单实现(冒泡和快排)(代码片段)

排序算法冒泡排序原理:把相邻的元素两两比较,根据大小来交换元素的位置。原始的冒泡排序是稳定排序。由于该排序的每一轮要遍历所以元素,轮转的次数和元素数量相当,所以时间复杂度是O(N^2)。java代码表达如下:importja... 查看详情

选择排序的算法和优化(代码片段)

正常的选择排序选择排序是每一次从待排序的数据元素中选出最小的一个元素,存放在序列的起始位置,直到全部待排序的数据元素排完。  分为三步:  ①、从待排序序列中,找到关键字最小的元素  ②、如果最小元素... 查看详情

简单排序算法(代码片段)

这里写目录标题冒泡排序选择排序插入排序希尔排序快速排序二分法查找冒泡排序两个for循环,两两进行比较,如果满足规则,则将两个数据进行交换publicint[]maopao()int[]arrays=1,3,9,5,11,66,85,97,101,588,469,258,147,369,456;for(... 查看详情

简单排序算法(代码片段)

这里写目录标题冒泡排序选择排序插入排序希尔排序快速排序二分法查找冒泡排序两个for循环,两两进行比较,如果满足规则,则将两个数据进行交换publicint[]maopao()int[]arrays=1,3,9,5,11,66,85,97,101,588,469,258,147,369,456;for(... 查看详情

基础算法之选择排序算法(代码片段)

基本思想:在要排序的一组数中,选出最小(或者最大)的一个数与第1个位置的数交换;然后在剩下的数当中再找最小(或者最大)的与第2个位置的数交换,依次类推,直到第n-1个元素(倒数第二个数)和第n个元素(最后一个... 查看详情