Block Merge Sort, též známý jako WikiSort je rychlý a stabilní O(n log n) řadící algoritmus, který používá O(1) paměti, navržený Mikem McFaddenem.

Algoritmus je ještě rychlejší, je-li vstup částečně setříděn, nebo může-li použít větší pole. Může být také modifikován tak, aby použil další dodatečnou paměť a tím zvýšil svou rychlost.

Block Merge Sort jak název napovídá se skládá z rozložení daného seznamu prvků do bloků, jejich setřídění a následnému slévání zpět. Aby dosáhl asymptotické složitosti O(n log n), kombinuje Block Merge Sort vždy alespoň dvě operace Merge sort a Insertion sort. Své jméno tedy dostal z porovnání dvou setříděných seznamů A a B, což je ve skutečnosti ekvivalentní rozložení seznamu A na rovnoměrné části nazývané Bloky (Block...), vložení každého bloku A do B dle speciálních pravidel a slévání (...Merge...) párů AB (...Sort). Jeden praktický algoritmus, využívající Block Merge Sort byl uveřejněn v roce 2008 [Pok-Son Kim a Arne Kutzner].

Vizualizace

Block Merge Sort (WikiSort)

Popis algoritmu

Vnější smyčka Block Sortu je identická s Merge Sortem a jeho řazením odspodu nahoru, kde každá úroveň třídění slévá páry pomocných polí A a B, dle velikosti 1 pak 2, pak 4, 8, 16 a tak dál, dokud nejsou obě pomocná pole zkombinována do samostatného pole. Blokový algoritmus slévání však raději namísto přímého slévání A a B rozdělí A na diskrétní bloky velikosti √A (výsledkem je √A bloků), vloží každý blok A do B tak, aby první hodnota každého bloku A byla menší nebo rovna hodnotě B, která se nachází přímo za ní. Pak lokálně slévá každý blok A s každou hodnotou B, která je mezi ní a následujícím blokem A. Jelikož slévání stále vyžaduje buffer, dostatečně velký na uložení slévaného bloku A, jsou k tomuto účelu rezervovány dvě oblasti v poli (známé jako interní buffer).

První dva bloky jsou proto modifikovány, aby obsahovaly první instanci každé hodnoty uvnitř A s originálním obsahem těchto bloků, které jsou dle nutnosti přehozeny. Zbývající bloky A jsou pak vloženy do B a slévány pomocí jednoho ze dvou bufferů jako swapový prostor. Tento postup provede přeuspořádání hodnot v bufferu. Jakmile jsou slity všechny bloky A a B každé části pole (pomocného pole) A a B pro danou úroveň MargeSortu, hodnoty v bufferu musí být setříděny, aby obnovily původní pořadí, takže musí přijít na řadu vkládání (Insertion). hodnoty v bufferu jsou pak přeuspořádány do jejich prvních setříděných pozic v poli. Tento postup se opakuje pro každou úroveň vnějšího třídění se sléváním odspodu nahoru. V tomto bodě již bude pole stabilně setříděno.

Analýza

BlockSort je velmi dobře navržen a velmi dobře testovatelný algoritmus. Na Internetu se nachází dostatečné množství různých implementací. Díky tomu lze jeho charakteristiky skvěle změřit. BlockSort je adaptivním tříděním ve dvou rovinách: nejprve přeskočí slévání pomocných polí A a B, pokud jsou již setříděny. Dále pak při slévání A a B, které jsou rozloženy na rovnoměrně velké bloky jsou bloky A přesunuty za B tak daleko, jak jen je to nutné a každý blok je sléván pouze s hodnotami B, které se nalézají ihned za nimi. Čím více jsou původní data setříděna, tím méně bude hodnot B, které je potřeba slévat do bloku A.

Výhody

BlockSort je stabilním třídícím algoritmem, který nevyžaduje dodatečnou počítačovou paměť, což je užitečné zejména, pokud nemáme dostatečně velkou paměť k alokování bufferu O(n). Pokud použijeme variantu BlockSortu s externím bufferem, můžeme paměť snižovat z výchozí O(n) na postupně menší a menší buffery a algoritmus bude nadále fungovat efektivně.

Nevýhody

BlockSort nevyužívá řazených rozsahů tak efektivně jako jiné algoritmy, například Timsort. BlockSort kontroluje tyto setříděné rozsahy pouze ve dvou úrovních: jako pomocná pole A a B a jako bloky A a B. Je také v porovnání s algoritmem Merge Sort hůře implementovatelný a nelze tak jednoduše paralelizovat.

Kód

0001.            /***********************************************************
0002. WikiSort (public domain license)
0004.  
0005. to run:
0006. javac WikiSort.java
0007. java WikiSort
0008.***********************************************************/
0009. 
0010.// the performance of WikiSort here seems to be completely at the mercy of the JIT compiler
0011.// sometimes it's 40% as fast, sometimes 80%, and either way it's a lot slower than the C code
0012. 
0013.import java.util.*;
0014.import java.lang.*;
0015.import java.io.*;
0016. 
0017.// class to test stable sorting (index will contain its original index in the array, to make sure it doesn't switch places with other items)
0018.class Test {
0019.    public int value;
0020.    public int index;
0021.}
0022. 
0023.class TestComparator implements Comparator<test> {
0024.    static int comparisons = 0;
0025.    public int compare(Test a, Test b) {
0026.        comparisons++;
0027.        if (a.value < b.value) return -1;
0028.        if (a.value > b.value) return 1;
0029.        return 0;
0030.    }
0031.}
0032. 
0033.// structure to represent ranges within the array
0034.class Range {
0035.    public int start;
0036.    public int end;
0037.     
0038.    public Range(int start1, int end1) {
0039.        start = start1;
0040.        end = end1;
0041.    }
0042.     
0043.    public Range() {
0044.        start = 0;
0045.        end = 0;
0046.    }
0047.     
0048.    void set(int start1, int end1) {
0049.        start = start1;
0050.        end = end1;
0051.    }
0052.     
0053.    int length() {
0054.        return end - start;
0055.    }
0056.}
0057. 
0058.class Pull {
0059.    public int from, to, count;
0060.    public Range range;
0061.    public Pull() { range = new Range(0, 0); }
0062.    void reset() {
0063.        range.set(0, 0);
0064.        from = 0;
0065.        to = 0;
0066.        count = 0;
0067.    }
0068.}
0069. 
0070.// calculate how to scale the index value to the range within the array
0071.// the bottom-up merge sort only operates on values that are powers of two,
0072.// so scale down to that power of two, then use a fraction to scale back again
0073.class Iterator {
0074.    public int size, power_of_two;
0075.    public int numerator, decimal;
0076.    public int denominator, decimal_step, numerator_step;
0077.     
0078.    // 63 -> 32, 64 -> 64, etc.
0079.    // this comes from Hacker's Delight
0080.    static int FloorPowerOfTwo(int value) {
0081.        int x = value;
0082.        x = x | (x >> 1);
0083.        x = x | (x >> 2);
0084.        x = x | (x >> 4);
0085.        x = x | (x >> 8);
0086.        x = x | (x >> 16);
0087.        return x - (x >> 1);
0088.    }
0089.     
0090.    Iterator(int size2, int min_level) {
0091.        size = size2;
0092.        power_of_two = FloorPowerOfTwo(size);
0093.        denominator = power_of_two/min_level;
0094.        numerator_step = size % denominator;
0095.        decimal_step = size/denominator;
0096.        begin();
0097.    }
0098.     
0099.    void begin() {
0100.        numerator = decimal = 0;
0101.    }
0102.     
0103.    Range nextRange() {
0104.        int start = decimal;
0105.         
0106.        decimal += decimal_step;
0107.        numerator += numerator_step;
0108.        if (numerator >= denominator) {
0109.            numerator -= denominator;
0110.            decimal++;
0111.        }
0112.         
0113.        return new Range(start, decimal);
0114.    }
0115.     
0116.    boolean finished() {
0117.        return (decimal >= size);
0118.    }
0119.     
0120.    boolean nextLevel() {
0121.        decimal_step += decimal_step;
0122.        numerator_step += numerator_step;
0123.        if (numerator_step >= denominator) {
0124.            numerator_step -= denominator;
0125.            decimal_step++;
0126.        }
0127.         
0128.        return (decimal_step < size);
0129.    }
0130.     
0131.    int length() {
0132.        return decimal_step;
0133.    }
0134.}
0135. 
0136.class WikiSorter<t> {
0137.    // use a small cache to speed up some of the operations
0138.    // since the cache size is fixed, it's still O(1) memory!
0139.    // just keep in mind that making it too small ruins the point (nothing will fit into it),
0140.    // and making it too large also ruins the point (so much for "low memory"!)
0141.    private static int cache_size = 512;
0142.    private T[] cache;
0143.     
0144.    // note that you can easily modify the above to allocate a dynamically sized cache
0145.    // good choices for the cache size are:
0146.    // (size + 1)/2 – turns into a full-speed standard merge sort since everything fits into the cache
0147.    // sqrt((size + 1)/2) + 1 – this will be the size of the A blocks at the largest level of merges,
0148.    // so a buffer of this size would allow it to skip using internal or in-place merges for anything
0149.    // 512 – chosen from careful testing as a good balance between fixed-size memory use and run time
0150.    // 0 – if the system simply cannot allocate any extra memory whatsoever, no memory works just fine
0151.     
0152.    public WikiSorter() {
0153.        @SuppressWarnings("unchecked")
0154.        T[] cache1 = (T[])new Object[cache_size];
0155.        if (cache1 == null) cache_size = 0;
0156.        else cache = cache1;
0157.    }
0158.     
0159.    public static <t> void sort(T[] array, Comparator<t> comp) {
0160.        new WikiSorter<t>().Sort(array, comp);
0161.    }
0162.     
0163.    // toolbox functions used by the sorter
0164.     
0165.    // find the index of the first value within the range that is equal to array[index]
0166.    int BinaryFirst(T array[], T value, Range range, Comparator<t> comp) {
0167.        int start = range.start, end = range.end - 1;
0168.        while (start < end) {
0169.            int mid = start + (end - start)/2;
0170.            if (comp.compare(array[mid], value) < 0)
0171.                start = mid + 1;
0172.            else
0173.                end = mid;
0174.        }
0175.        if (start == range.end - 1 && comp.compare(array[start], value) < 0) start++;
0176.        return start;
0177.    }
0178.     
0179.    // find the index of the last value within the range that is equal to array[index], plus 1
0180.    int BinaryLast(T array[], T value, Range range, Comparator<t> comp) {
0181.        int start = range.start, end = range.end - 1;
0182.        while (start < end) {
0183.            int mid = start + (end - start)/2;
0184.            if (comp.compare(value, array[mid]) >= 0)
0185.                start = mid + 1;
0186.            else
0187.                end = mid;
0188.        }
0189.        if (start == range.end - 1 && comp.compare(value, array[start]) >= 0) start++;
0190.        return start;
0191.    }
0192.     
0193.    // combine a linear search with a binary search to reduce the number of comparisons in situations
0194.    // where have some idea as to how many unique values there are and where the next value might be
0195.    int FindFirstForward(T array[], T value, Range range, Comparator<t> comp, int unique) {
0196.        if (range.length() == 0) return range.start;
0197.        int index, skip = Math.max(range.length()/unique, 1);
0198.         
0199.        for (index = range.start + skip; comp.compare(array[index - 1], value) < 0; index += skip)
0200.            if (index >= range.end - skip)
0201.                return BinaryFirst(array, value, new Range(index, range.end), comp);
0202.         
0203.        return BinaryFirst(array, value, new Range(index - skip, index), comp);
0204.    }
0205.     
0206.    int FindLastForward(T array[], T value, Range range, Comparator<t> comp, int unique) {
0207.        if (range.length() == 0) return range.start;
0208.        int index, skip = Math.max(range.length()/unique, 1);
0209.         
0210.        for (index = range.start + skip; comp.compare(value, array[index - 1]) >= 0; index += skip)
0211.            if (index >= range.end - skip)
0212.                return BinaryLast(array, value, new Range(index, range.end), comp);
0213.         
0214.        return BinaryLast(array, value, new Range(index - skip, index), comp);
0215.    }
0216.     
0217.    int FindFirstBackward(T array[], T value, Range range, Comparator<t> comp, int unique) {
0218.        if (range.length() == 0) return range.start;
0219.        int index, skip = Math.max(range.length()/unique, 1);
0220.         
0221.        for (index = range.end - skip; index > range.start && comp.compare(array[index - 1], value) >= 0; index -= skip)
0222.            if (index < range.start + skip)
0223.                return BinaryFirst(array, value, new Range(range.start, index), comp);
0224.         
0225.        return BinaryFirst(array, value, new Range(index, index + skip), comp);
0226.    }
0227.     
0228.    int FindLastBackward(T array[], T value, Range range, Comparator<t> comp, int unique) {
0229.        if (range.length() == 0) return range.start;
0230.        int index, skip = Math.max(range.length()/unique, 1);
0231.         
0232.        for (index = range.end - skip; index > range.start && comp.compare(value, array[index - 1]) < 0; index -= skip)
0233.            if (index < range.start + skip)
0234.                return BinaryLast(array, value, new Range(range.start, index), comp);
0235.         
0236.        return BinaryLast(array, value, new Range(index, index + skip), comp);
0237.    }
0238.     
0239.    // n^2 sorting algorithm used to sort tiny chunks of the full array
0240.    void InsertionSort(T array[], Range range, Comparator<t> comp) {
0241.        for (int j, i = range.start + 1; i < range.end; i++) {
0242.            T temp = array[i];
0243.            for (j = i; j > range.start && comp.compare(temp, array[j - 1]) < 0; j--)
0244.                array[j] = array[j - 1];
0245.            array[j] = temp;
0246.        }
0247.    }
0248.     
0249.    // reverse a range of values within the array
0250.    void Reverse(T array[], Range range) {
0251.        for (int index = range.length()/2 - 1; index >= 0; index--) {
0252.            T swap = array[range.start + index];
0253.            array[range.start + index] = array[range.end - index - 1];
0254.            array[range.end - index - 1] = swap;
0255.        }
0256.    }
0257.     
0258.    // swap a series of values in the array
0259.    void BlockSwap(T array[], int start1, int start2, int block_size) {
0260.        for (int index = 0; index < block_size; index++) {
0261.            T swap = array[start1 + index];
0262.            array[start1 + index] = array[start2 + index];
0263.            array[start2 + index] = swap;
0264.        }
0265.    }
0266.     
0267.    // rotate the values in an array ([0 1 2 3] becomes [1 2 3 0] if we rotate by 1)
0268.    // this assumes that 0 <= amount <= range.length()
0269.    void Rotate(T array[], int amount, Range range, boolean use_cache) {
0270.        if (range.length() == 0) return;
0271.         
0272.        int split;
0273.        if (amount >= 0)
0274.            split = range.start + amount;
0275.        else
0276.            split = range.end + amount;
0277.         
0278.        Range range1 = new Range(range.start, split);
0279.        Range range2 = new Range(split, range.end);
0280.         
0281.        if (use_cache) {
0282.            // if the smaller of the two ranges fits into the cache, it's *slightly* faster copying it there and shifting the elements over
0283.            if (range1.length() <= range2.length()) {
0284.                if (range1.length() <= cache_size) {
0285.                    if (cache != null) {
0286.                        java.lang.System.arraycopy(array, range1.start, cache, 0, range1.length());
0287.                        java.lang.System.arraycopy(array, range2.start, array, range1.start, range2.length());
0288.                        java.lang.System.arraycopy(cache, 0, array, range1.start + range2.length(), range1.length());
0289.                    }
0290.                    return;
0291.                }
0292.            } else {
0293.                if (range2.length() <= cache_size) {
0294.                    if (cache != null) {
0295.                        java.lang.System.arraycopy(array, range2.start, cache, 0, range2.length());
0296.                        java.lang.System.arraycopy(array, range1.start, array, range2.end - range1.length(), range1.length());
0297.                        java.lang.System.arraycopy(cache, 0, array, range1.start, range2.length());
0298.                    }
0299.                    return;
0300.                }
0301.            }
0302.        }
0303.         
0304.        Reverse(array, range1);
0305.        Reverse(array, range2);
0306.        Reverse(array, range);
0307.    }
0308.     
0309.    // merge two ranges from one array and save the results into a different array
0310.    void MergeInto(T from[], Range A, Range B, Comparator<t> comp, T into[], int at_index) {
0311.        int A_index = A.start;
0312.        int B_index = B.start;
0313.        int insert_index = at_index;
0314.        int A_last = A.end;
0315.        int B_last = B.end;
0316.         
0317.        while (true) {
0318.            if (comp.compare(from[B_index], from[A_index]) >= 0) {
0319.                into[insert_index] = from[A_index];
0320.                A_index++;
0321.                insert_index++;
0322.                if (A_index == A_last) {
0323.                    // copy the remainder of B into the final array
0324.                    java.lang.System.arraycopy(from, B_index, into, insert_index, B_last - B_index);
0325.                    break;
0326.                }
0327.            } else {
0328.                into[insert_index] = from[B_index];
0329.                B_index++;
0330.                insert_index++;
0331.                if (B_index == B_last) {
0332.                    // copy the remainder of A into the final array
0333.                    java.lang.System.arraycopy(from, A_index, into, insert_index, A_last - A_index);
0334.                    break;
0335.                }
0336.            }
0337.        }
0338.    }
0339.     
0340.    // merge operation using an external buffer,
0341.    void MergeExternal(T array[], Range A, Range B, Comparator<t> comp) {
0342.        // A fits into the cache, so use that instead of the internal buffer
0343.        int A_index = 0;
0344.        int B_index = B.start;
0345.        int insert_index = A.start;
0346.        int A_last = A.length();
0347.        int B_last = B.end;
0348.         
0349.        if (B.length() > 0 && A.length() > 0) {
0350.            while (true) {
0351.                if (comp.compare(array[B_index], cache[A_index]) >= 0) {
0352.                    array[insert_index] = cache[A_index];
0353.                    A_index++;
0354.                    insert_index++;
0355.                    if (A_index == A_last) break;
0356.                } else {
0357.                    array[insert_index] = array[B_index];
0358.                    B_index++;
0359.                    insert_index++;
0360.                    if (B_index == B_last) break;
0361.                }
0362.            }
0363.        }
0364.         
0365.        // copy the remainder of A into the final array
0366.        if (cache != null) java.lang.System.arraycopy(cache, A_index, array, insert_index, A_last - A_index);
0367.    }
0368.     
0369.    // merge operation using an internal buffer
0370.    void MergeInternal(T array[], Range A, Range B, Comparator<t> comp, Range buffer) {
0371.        // whenever we find a value to add to the final array, swap it with the value that's already in that spot
0372.        // when this algorithm is finished, 'buffer' will contain its original contents, but in a different order
0373.        int A_count = 0, B_count = 0, insert = 0;
0374.         
0375.        if (B.length() > 0 && A.length() > 0) {
0376.            while (true) {
0377.                if (comp.compare(array[B.start + B_count], array[buffer.start + A_count]) >= 0) {
0378.                    T swap = array[A.start + insert];
0379.                    array[A.start + insert] = array[buffer.start + A_count];
0380.                    array[buffer.start + A_count] = swap;
0381.                    A_count++;
0382.                    insert++;
0383.                    if (A_count >= A.length()) break;
0384.                } else {
0385.                    T swap = array[A.start + insert];
0386.                    array[A.start + insert] = array[B.start + B_count];
0387.                    array[B.start + B_count] = swap;
0388.                    B_count++;
0389.                    insert++;
0390.                    if (B_count >= B.length()) break;
0391.                }
0392.            }
0393.        }
0394.         
0395.        // swap the remainder of A into the final array
0396.        BlockSwap(array, buffer.start + A_count, A.start + insert, A.length() - A_count);
0397.    }
0398.     
0399.    // merge operation without a buffer
0400.    void MergeInPlace(T array[], Range A, Range B, Comparator<t> comp) {
0401.        if (A.length() == 0 || B.length() == 0) return;
0402.         
0403.        /*
0404.         this just repeatedly binary searches into B and rotates A into position.
0405.         the paper suggests using the 'rotation-based Hwang and Lin algorithm' here,
0406.         but I decided to stick with this because it had better situational performance
0407.          
0408.         (Hwang and Lin is designed for merging subarrays of very different sizes,
0409.         but WikiSort almost always uses subarrays that are roughly the same size)
0410.          
0411.         normally this is incredibly suboptimal, but this function is only called
0412.         when none of the A or B blocks in any subarray contained 2√A unique values,
0413.         which places a hard limit on the number of times this will ACTUALLY need
0414.         to binary search and rotate.
0415.          
0416.         according to my analysis the worst case is √A rotations performed on √A items
0417.         once the constant factors are removed, which ends up being O(n)
0418.          
0419.         again, this is NOT a general-purpose solution – it only works well in this case!
0420.         kind of like how the O(n^2) insertion sort is used in some places
0421.         */
0422.         
0423.        A = new Range(A.start, A.end);
0424.        B = new Range(B.start, B.end);
0425.         
0426.        while (true) {
0427.            // find the first place in B where the first item in A needs to be inserted
0428.            int mid = BinaryFirst(array, array[A.start], B, comp);
0429.             
0430.            // rotate A into place
0431.            int amount = mid - A.end;
0432.            Rotate(array, -amount, new Range(A.start, mid), true);
0433.            if (B.end == mid) break;
0434.             
0435.            // calculate the new A and B ranges
0436.            B.start = mid;
0437.            A.set(A.start + amount, B.start);
0438.            A.start = BinaryLast(array, array[A.start], A, comp);
0439.            if (A.length() == 0) break;
0440.        }
0441.    }
0442.     
0443.    void NetSwap(T array[], int order[], Range range, Comparator<t> comp, int x, int y) {
0444.        int compare = comp.compare(array[range.start + x], array[range.start + y]);
0445.        if (compare > 0 || (order[x] > order[y] && compare == 0)) {
0446.            T swap = array[range.start + x];
0447.            array[range.start + x] = array[range.start + y];
0448.            array[range.start + y] = swap;
0449.            int swap2 = order[x];
0450.            order[x] = order[y];
0451.            order[y] = swap2;
0452.        }
0453.    }
0454.     
0455.    // bottom-up merge sort combined with an in-place merge algorithm for O(1) memory use
0456.    void Sort(T array[], Comparator<t> comp) {
0457.        int size = array.length;
0458.         
0459.        // if the array is of size 0, 1, 2, or 3, just sort them like so:
0460.        if (size < 4) {
0461.            if (size == 3) {
0462.                // hard-coded insertion sort
0463.                if (comp.compare(array[1], array[0]) < 0) {
0464.                    T swap = array[0];
0465.                    array[0] = array[1];
0466.                    array[1] = swap;
0467.                }
0468.                if (comp.compare(array[2], array[1]) < 0) {
0469.                    T swap = array[1];
0470.                    array[1] = array[2];
0471.                    array[2] = swap;
0472.                    if (comp.compare(array[1], array[0]) < 0) {
0473.                        swap = array[0];
0474.                        array[0] = array[1];
0475.                        array[1] = swap;
0476.                    }
0477.                }
0478.            } else if (size == 2) {
0479.                // swap the items if they're out of order
0480.                if (comp.compare(array[1], array[0]) < 0) {
0481.                    T swap = array[0];
0482.                    array[0] = array[1];
0483.                    array[1] = swap;
0484.                }
0485.            }
0486.             
0487.            return;
0488.        }
0489.         
0490.        // sort groups of 4-8 items at a time using an unstable sorting network,
0491.        // but keep track of the original item orders to force it to be stable
0492.        // http://pages.ripco.net/~jgamble/nw.html
0493.        Iterator iterator = new Iterator(size, 4);
0494.        while (!iterator.finished()) {
0495.            int order[] = { 0, 1, 2, 3, 4, 5, 6, 7 };
0496.            Range range = iterator.nextRange();
0497.             
0498.            if (range.length() == 8) {
0499.                NetSwap(array, order, range, comp, 0, 1); NetSwap(array, order, range, comp, 2, 3);
0500.                NetSwap(array, order, range, comp, 4, 5); NetSwap(array, order, range, comp, 6, 7);
0501.                NetSwap(array, order, range, comp, 0, 2); NetSwap(array, order, range, comp, 1, 3);
0502.                NetSwap(array, order, range, comp, 4, 6); NetSwap(array, order, range, comp, 5, 7);
0503.                NetSwap(array, order, range, comp, 1, 2); NetSwap(array, order, range, comp, 5, 6);
0504.                NetSwap(array, order, range, comp, 0, 4); NetSwap(array, order, range, comp, 3, 7);
0505.                NetSwap(array, order, range, comp, 1, 5); NetSwap(array, order, range, comp, 2, 6);
0506.                NetSwap(array, order, range, comp, 1, 4); NetSwap(array, order, range, comp, 3, 6);
0507.                NetSwap(array, order, range, comp, 2, 4); NetSwap(array, order, range, comp, 3, 5);
0508.                NetSwap(array, order, range, comp, 3, 4);
0509.                 
0510.            } else if (range.length() == 7) {
0511.                NetSwap(array, order, range, comp, 1, 2); NetSwap(array, order, range, comp, 3, 4); NetSwap(array, order, range, comp, 5, 6);
0512.                NetSwap(array, order, range, comp, 0, 2); NetSwap(array, order, range, comp, 3, 5); NetSwap(array, order, range, comp, 4, 6);
0513.                NetSwap(array, order, range, comp, 0, 1); NetSwap(array, order, range, comp, 4, 5); NetSwap(array, order, range, comp, 2, 6);
0514.                NetSwap(array, order, range, comp, 0, 4); NetSwap(array, order, range, comp, 1, 5);
0515.                NetSwap(array, order, range, comp, 0, 3); NetSwap(array, order, range, comp, 2, 5);
0516.                NetSwap(array, order, range, comp, 1, 3); NetSwap(array, order, range, comp, 2, 4);
0517.                NetSwap(array, order, range, comp, 2, 3);
0518.                 
0519.            } else if (range.length() == 6) {
0520.                NetSwap(array, order, range, comp, 1, 2); NetSwap(array, order, range, comp, 4, 5);
0521.                NetSwap(array, order, range, comp, 0, 2); NetSwap(array, order, range, comp, 3, 5);
0522.                NetSwap(array, order, range, comp, 0, 1); NetSwap(array, order, range, comp, 3, 4); NetSwap(array, order, range, comp, 2, 5);
0523.                NetSwap(array, order, range, comp, 0, 3); NetSwap(array, order, range, comp, 1, 4);
0524.                NetSwap(array, order, range, comp, 2, 4); NetSwap(array, order, range, comp, 1, 3);
0525.                NetSwap(array, order, range, comp, 2, 3);
0526.                 
0527.            } else if (range.length() == 5) {
0528.                NetSwap(array, order, range, comp, 0, 1); NetSwap(array, order, range, comp, 3, 4);
0529.                NetSwap(array, order, range, comp, 2, 4);
0530.                NetSwap(array, order, range, comp, 2, 3); NetSwap(array, order, range, comp, 1, 4);
0531.                NetSwap(array, order, range, comp, 0, 3);
0532.                NetSwap(array, order, range, comp, 0, 2); NetSwap(array, order, range, comp, 1, 3);
0533.                NetSwap(array, order, range, comp, 1, 2);
0534.                 
0535.            } else if (range.length() == 4) {
0536.                NetSwap(array, order, range, comp, 0, 1); NetSwap(array, order, range, comp, 2, 3);
0537.                NetSwap(array, order, range, comp, 0, 2); NetSwap(array, order, range, comp, 1, 3);
0538.                NetSwap(array, order, range, comp, 1, 2);
0539.            }
0540.        }
0541.        if (size < 8) return;
0542.         
0543.        // we need to keep track of a lot of ranges during this sort!
0544.        Range buffer1 = new Range(), buffer2 = new Range();
0545.        Range blockA = new Range(), blockB = new Range();
0546.        Range lastA = new Range(), lastB = new Range();
0547.        Range firstA = new Range();
0548.        Range A = new Range(), B = new Range();
0549.         
0550.        Pull[] pull = new Pull[2];
0551.        pull[0] = new Pull();
0552.        pull[1] = new Pull();
0553.         
0554.        // then merge sort the higher levels, which can be 8-15, 16-31, 32-63, 64-127, etc.
0555.        while (true) {
0556.             
0557.            // if every A and B block will fit into the cache, use a special branch specifically for merging with the cache
0558.            // (we use < rather than <= since the block size might be one more than iterator.length())
0559.            if (iterator.length() < cache_size) {
0560.                 
0561.                // if four subarrays fit into the cache, it's faster to merge both pairs of subarrays into the cache,
0562.                // then merge the two merged subarrays from the cache back into the original array
0563.                if ((iterator.length() + 1) * 4 <= cache_size && iterator.length() * 4 <= size) {
0564.                    iterator.begin();
0565.                    while (!iterator.finished()) {
0566.                        // merge A1 and B1 into the cache
0567.                        Range A1 = iterator.nextRange();
0568.                        Range B1 = iterator.nextRange();
0569.                        Range A2 = iterator.nextRange();
0570.                        Range B2 = iterator.nextRange();
0571.                         
0572.                        if (comp.compare(array[B1.end - 1], array[A1.start]) < 0) {
0573.                            // the two ranges are in reverse order, so copy them in reverse order into the cache
0574.                            java.lang.System.arraycopy(array, A1.start, cache, B1.length(), A1.length());
0575.                            java.lang.System.arraycopy(array, B1.start, cache, 0, B1.length());
0576.                        } else if (comp.compare(array[B1.start], array[A1.end - 1]) < 0) {
0577.                            // these two ranges weren't already in order, so merge them into the cache
0578.                            MergeInto(array, A1, B1, comp, cache, 0);
0579.                        } else {
0580.                            // if A1, B1, A2, and B2 are all in order, skip doing anything else
0581.                            if (comp.compare(array[B2.start], array[A2.end - 1]) >= 0 && comp.compare(array[A2.start], array[B1.end - 1]) >= 0) continue;
0582.                             
0583.                            // copy A1 and B1 into the cache in the same order
0584.                            java.lang.System.arraycopy(array, A1.start, cache, 0, A1.length());
0585.                            java.lang.System.arraycopy(array, B1.start, cache, A1.length(), B1.length());
0586.                        }
0587.                        A1.set(A1.start, B1.end);
0588.                         
0589.                        // merge A2 and B2 into the cache
0590.                        if (comp.compare(array[B2.end - 1], array[A2.start]) < 0) {
0591.                            // the two ranges are in reverse order, so copy them in reverse order into the cache
0592.                            java.lang.System.arraycopy(array, A2.start, cache, A1.length() + B2.length(), A2.length());
0593.                            java.lang.System.arraycopy(array, B2.start, cache, A1.length(), B2.length());
0594.                        } else if (comp.compare(array[B2.start], array[A2.end - 1]) < 0) {
0595.                            // these two ranges weren't already in order, so merge them into the cache
0596.                            MergeInto(array, A2, B2, comp, cache, A1.length());
0597.                        } else {
0598.                            // copy A2 and B2 into the cache in the same order
0599.                            java.lang.System.arraycopy(array, A2.start, cache, A1.length(), A2.length());
0600.                            java.lang.System.arraycopy(array, B2.start, cache, A1.length() + A2.length(), B2.length());
0601.                        }
0602.                        A2.set(A2.start, B2.end);
0603.                         
0604.                        // merge A1 and A2 from the cache into the array
0605.                        Range A3 = new Range(0, A1.length());
0606.                        Range B3 = new Range(A1.length(), A1.length() + A2.length());
0607.                         
0608.                        if (comp.compare(cache[B3.end - 1], cache[A3.start]) < 0) {
0609.                            // the two ranges are in reverse order, so copy them in reverse order into the cache
0610.                            java.lang.System.arraycopy(cache, A3.start, array, A1.start + A2.length(), A3.length());
0611.                            java.lang.System.arraycopy(cache, B3.start, array, A1.start, B3.length());
0612.                        } else if (comp.compare(cache[B3.start], cache[A3.end - 1]) < 0) {
0613.                            // these two ranges weren't already in order, so merge them back into the array
0614.                            MergeInto(cache, A3, B3, comp, array, A1.start);
0615.                        } else {
0616.                            // copy A3 and B3 into the array in the same order
0617.                            java.lang.System.arraycopy(cache, A3.start, array, A1.start, A3.length());
0618.                            java.lang.System.arraycopy(cache, B3.start, array, A1.start + A1.length(), B3.length());
0619.                        }
0620.                    }
0621.                     
0622.                    // we merged two levels at the same time, so we're done with this level already
0623.                    // (iterator.nextLevel() is called again at the bottom of this outer merge loop)
0624.                    iterator.nextLevel();
0625.                     
0626.                } else {
0627.                    iterator.begin();
0628.                    while (!iterator.finished()) {
0629.                        A = iterator.nextRange();
0630.                        B = iterator.nextRange();
0631.                         
0632.                        if (comp.compare(array[B.end - 1], array[A.start]) < 0) {
0633.                            // the two ranges are in reverse order, so a simple rotation should fix it
0634.                            Rotate(array, A.length(), new Range(A.start, B.end), true);
0635.                        } else if (comp.compare(array[B.start], array[A.end - 1]) < 0) {
0636.                            // these two ranges weren't already in order, so we'll need to merge them!
0637.                            java.lang.System.arraycopy(array, A.start, cache, 0, A.length());
0638.                            MergeExternal(array, A, B, comp);
0639.                        }
0640.                    }
0641.                }
0642.            } else {
0643.                // this is where the in-place merge logic starts!
0644.                // 1. pull out two internal buffers each containing √A unique values
0645.                //     1a. adjust block_size and buffer_size if we couldn't find enough unique values
0646.                // 2. loop over the A and B subarrays within this level of the merge sort
0647.                //     3. break A and B into blocks of size 'block_size'
0648.                //     4. "tag" each of the A blocks with values from the first internal buffer
0649.                //     5. roll the A blocks through the B blocks and drop/rotate them where they belong
0650.                //     6. merge each A block with any B values that follow, using the cache or the second internal buffer
0651.                // 7. sort the second internal buffer if it exists
0652.                // 8. redistribute the two internal buffers back into the array
0653.                 
0654.                int block_size = (int)Math.sqrt(iterator.length());
0655.                int buffer_size = iterator.length()/block_size + 1;
0656.                 
0657.                // as an optimization, we really only need to pull out the internal buffers once for each level of merges
0658.                // after that we can reuse the same buffers over and over, then redistribute it when we're finished with this level
0659.                int index, last, count, pull_index = 0;
0660.                buffer1.set(0, 0);
0661.                buffer2.set(0, 0);
0662.                 
0663.                pull[0].reset();
0664.                pull[1].reset();
0665.                 
0666.                // find two internal buffers of size 'buffer_size' each
0667.                int find = buffer_size + buffer_size;
0668.                boolean find_separately = false;
0669.                 
0670.                if (block_size <= cache_size) {
0671.                    // if every A block fits into the cache then we won't need the second internal buffer,
0672.                    // so we really only need to find 'buffer_size' unique values
0673.                    find = buffer_size;
0674.                } else if (find > iterator.length()) {
0675.                    // we can't fit both buffers into the same A or B subarray, so find two buffers separately
0676.                    find = buffer_size;
0677.                    find_separately = true;
0678.                }
0679.                 
0680.                // we need to find either a single contiguous space containing 2√A unique values (which will be split up into two buffers of size √A each),
0681.                // or we need to find one buffer of < 2√A unique values, and a second buffer of √A unique values,
0682.                // OR if we couldn't find that many unique values, we need the largest possible buffer we can get
0683.                 
0684.                // in the case where it couldn't find a single buffer of at least √A unique values,
0685.                // all of the Merge steps must be replaced by a different merge algorithm (MergeInPlace)
0686.                 
0687.                iterator.begin();
0688.                while (!iterator.finished()) {
0689.                    A = iterator.nextRange();
0690.                    B = iterator.nextRange();
0691.                     
0692.                    // check A for the number of unique values we need to fill an internal buffer
0693.                    // these values will be pulled out to the start of A
0694.                    for (last = A.start, count = 1; count < find; last = index, count++) {
0695.                        index = FindLastForward(array, array[last], new Range(last + 1, A.end), comp, find - count);
0696.                        if (index == A.end) break;
0697.                    }
0698.                    index = last;
0699.                     
0700.                    if (count >= buffer_size) {
0701.                        // keep track of the range within the array where we'll need to "pull out" these values to create the internal buffer
0702.                        pull[pull_index].range.set(A.start, B.end);
0703.                        pull[pull_index].count = count;
0704.                        pull[pull_index].from = index;
0705.                        pull[pull_index].to = A.start;
0706.                        pull_index = 1;
0707.                         
0708.                        if (count == buffer_size + buffer_size) {
0709.                            // we were able to find a single contiguous section containing 2√A unique values,
0710.                            // so this section can be used to contain both of the internal buffers we'll need
0711.                            buffer1.set(A.start, A.start + buffer_size);
0712.                            buffer2.set(A.start + buffer_size, A.start + count);
0713.                            break;
0714.                        } else if (find == buffer_size + buffer_size) {
0715.                            // we found a buffer that contains at least √A unique values, but did not contain the full 2√A unique values,
0716.                            // so we still need to find a second separate buffer of at least √A unique values
0717.                            buffer1.set(A.start, A.start + count);
0718.                            find = buffer_size;
0719.                        } else if (block_size <= cache_size) {
0720.                            // we found the first and only internal buffer that we need, so we're done!
0721.                            buffer1.set(A.start, A.start + count);
0722.                            break;
0723.                        } else if (find_separately) {
0724.                            // found one buffer, but now find the other one
0725.                            buffer1 = new Range(A.start, A.start + count);
0726.                            find_separately = false;
0727.                        } else {
0728.                            // we found a second buffer in an 'A' subarray containing √A unique values, so we're done!
0729.                            buffer2.set(A.start, A.start + count);
0730.                            break;
0731.                        }
0732.                    } else if (pull_index == 0 && count > buffer1.length()) {
0733.                        // keep track of the largest buffer we were able to find
0734.                        buffer1.set(A.start, A.start + count);
0735.                         
0736.                        pull[pull_index].range.set(A.start, B.end);
0737.                        pull[pull_index].count = count;
0738.                        pull[pull_index].from = index;
0739.                        pull[pull_index].to = A.start;
0740.                    }
0741.                     
0742.                    // check B for the number of unique values we need to fill an internal buffer
0743.                    // these values will be pulled out to the end of B
0744.                    for (last = B.end - 1, count = 1; count < find; last = index - 1, count++) {
0745.                        index = FindFirstBackward(array, array[last], new Range(B.start, last), comp, find - count);
0746.                        if (index == B.start) break;
0747.                    }
0748.                    index = last;
0749.                     
0750.                    if (count >= buffer_size) {
0751.                        // keep track of the range within the array where we'll need to "pull out" these values to create the internal buffer
0752.                        pull[pull_index].range.set(A.start, B.end);
0753.                        pull[pull_index].count = count;
0754.                        pull[pull_index].from = index;
0755.                        pull[pull_index].to = B.end;
0756.                        pull_index = 1;
0757.                         
0758.                        if (count == buffer_size + buffer_size) {
0759.                            // we were able to find a single contiguous section containing 2√A unique values,
0760.                            // so this section can be used to contain both of the internal buffers we'll need
0761.                            buffer1.set(B.end - count, B.end - buffer_size);
0762.                            buffer2.set(B.end - buffer_size, B.end);
0763.                            break;
0764.                        } else if (find == buffer_size + buffer_size) {
0765.                            // we found a buffer that contains at least √A unique values, but did not contain the full 2√A unique values,
0766.                            // so we still need to find a second separate buffer of at least √A unique values
0767.                            buffer1.set(B.end - count, B.end);
0768.                            find = buffer_size;
0769.                        } else if (block_size <= cache_size) {
0770.                            // we found the first and only internal buffer that we need, so we're done!
0771.                            buffer1.set(B.end - count, B.end);
0772.                            break;
0773.                        } else if (find_separately) {
0774.                            // found one buffer, but now find the other one
0775.                            buffer1 = new Range(B.end - count, B.end);
0776.                            find_separately = false;
0777.                        } else {
0778.                            // buffer2 will be pulled out from a 'B' subarray, so if the first buffer was pulled out from the corresponding 'A' subarray,
0779.                            // we need to adjust the end point for that A subarray so it knows to stop redistributing its values before reaching buffer2
0780.                            if (pull[0].range.start == A.start) pull[0].range.end -= pull[1].count;
0781.                             
0782.                            // we found a second buffer in an 'B' subarray containing √A unique values, so we're done!
0783.                            buffer2.set(B.end - count, B.end);
0784.                            break;
0785.                        }
0786.                    } else if (pull_index == 0 && count > buffer1.length()) {
0787.                        // keep track of the largest buffer we were able to find
0788.                        buffer1.set(B.end - count, B.end);
0789.                         
0790.                        pull[pull_index].range.set(A.start, B.end);
0791.                        pull[pull_index].count = count;
0792.                        pull[pull_index].from = index;
0793.                        pull[pull_index].to = B.end;
0794.                    }
0795.                }
0796.                 
0797.                // pull out the two ranges so we can use them as internal buffers
0798.                for (pull_index = 0; pull_index < 2; pull_index++) {
0799.                    int length = pull[pull_index].count;
0800.                     
0801.                    if (pull[pull_index].to < pull[pull_index].from) {
0802.                        // we're pulling the values out to the left, which means the start of an A subarray
0803.                        index = pull[pull_index].from;
0804.                        for (count = 1; count < length; count++) {
0805.                            index = FindFirstBackward(array, array[index - 1], new Range(pull[pull_index].to, pull[pull_index].from - (count - 1)), comp, length - count);
0806.                            Range range = new Range(index + 1, pull[pull_index].from + 1);
0807.                            Rotate(array, range.length() - count, range, true);
0808.                            pull[pull_index].from = index + count;
0809.                        }
0810.                    } else if (pull[pull_index].to > pull[pull_index].from) {
0811.                        // we're pulling values out to the right, which means the end of a B subarray
0812.                        index = pull[pull_index].from + 1;
0813.                        for (count = 1; count < length; count++) {
0814.                            index = FindLastForward(array, array[index], new Range(index, pull[pull_index].to), comp, length - count);
0815.                            Range range = new Range(pull[pull_index].from, index - 1);
0816.                            Rotate(array, count, range, true);
0817.                            pull[pull_index].from = index - 1 - count;
0818.                        }
0819.                    }
0820.                }
0821.                 
0822.                // adjust block_size and buffer_size based on the values we were able to pull out
0823.                buffer_size = buffer1.length();
0824.                block_size = iterator.length()/buffer_size + 1;
0825.                 
0826.                // the first buffer NEEDS to be large enough to tag each of the evenly sized A blocks,
0827.                // so this was originally here to test the math for adjusting block_size above
0828.                //if ((iterator.length() + 1)/block_size > buffer_size) throw new RuntimeException();
0829.                 
0830.                // now that the two internal buffers have been created, it's time to merge each A+B combination at this level of the merge sort!
0831.                iterator.begin();
0832.                while (!iterator.finished()) {
0833.                    A = iterator.nextRange();
0834.                    B = iterator.nextRange();
0835.                     
0836.                    // remove any parts of A or B that are being used by the internal buffers
0837.                    int start = A.start;
0838.                    if (start == pull[0].range.start) {
0839.                        if (pull[0].from > pull[0].to) {
0840.                            A.start += pull[0].count;
0841.                             
0842.                            // if the internal buffer takes up the entire A or B subarray, then there's nothing to merge
0843.                            // this only happens for very small subarrays, like √4 = 2, 2 * (2 internal buffers) = 4,
0844.                            // which also only happens when cache_size is small or 0 since it'd otherwise use MergeExternal
0845.                            if (A.length() == 0) continue;
0846.                        } else if (pull[0].from < pull[0].to) {
0847.                            B.end -= pull[0].count;
0848.                            if (B.length() == 0) continue;
0849.                        }
0850.                    }
0851.                    if (start == pull[1].range.start) {
0852.                        if (pull[1].from > pull[1].to) {
0853.                            A.start += pull[1].count;
0854.                            if (A.length() == 0) continue;
0855.                        } else if (pull[1].from < pull[1].to) {
0856.                            B.end -= pull[1].count;
0857.                            if (B.length() == 0) continue;
0858.                        }
0859.                    }
0860.                     
0861.                    if (comp.compare(array[B.end - 1], array[A.start]) < 0) {
0862.                        // the two ranges are in reverse order, so a simple rotation should fix it
0863.                        Rotate(array, A.length(), new Range(A.start, B.end), true);
0864.                    } else if (comp.compare(array[A.end], array[A.end - 1]) < 0) {
0865.                        // these two ranges weren't already in order, so we'll need to merge them!
0866.                         
0867.                        // break the remainder of A into blocks. firstA is the uneven-sized first A block
0868.                        blockA.set(A.start, A.end);
0869.                        firstA.set(A.start, A.start + blockA.length() % block_size);
0870.                         
0871.                        // swap the first value of each A block with the value in buffer1
0872.                        int indexA = buffer1.start;
0873.                        for (index = firstA.end; index < blockA.end; index += block_size)  {
0874.                            T swap = array[indexA];
0875.                            array[indexA] = array[index];
0876.                            array[index] = swap;
0877.                            indexA++;
0878.                        }
0879.                         
0880.                        // start rolling the A blocks through the B blocks!
0881.                        // whenever we leave an A block behind, we'll need to merge the previous A block with any B blocks that follow it, so track that information as well
0882.                        lastA.set(firstA.start, firstA.end);
0883.                        lastB.set(0, 0);
0884.                        blockB.set(B.start, B.start + Math.min(block_size, B.length()));
0885.                        blockA.start += firstA.length();
0886.                        indexA = buffer1.start;
0887.                         
0888.                        // if the first unevenly sized A block fits into the cache, copy it there for when we go to Merge it
0889.                        // otherwise, if the second buffer is available, block swap the contents into that
0890.                        if (lastA.length() <= cache_size && cache != null)
0891.                            java.lang.System.arraycopy(array, lastA.start, cache, 0, lastA.length());
0892.                        else if (buffer2.length() > 0)
0893.                            BlockSwap(array, lastA.start, buffer2.start, lastA.length());
0894.                         
0895.                        if (blockA.length() > 0) {
0896.                            while (true) {
0897.                                // if there's a previous B block and the first value of the minimum A block is <= the last value of the previous B block,
0898.                                // then drop that minimum A block behind. or if there are no B blocks left then keep dropping the remaining A blocks.
0899.                                if ((lastB.length() > 0 && comp.compare(array[lastB.end - 1], array[indexA]) >= 0) || blockB.length() == 0) {
0900.                                    // figure out where to split the previous B block, and rotate it at the split
0901.                                    int B_split = BinaryFirst(array, array[indexA], lastB, comp);
0902.                                    int B_remaining = lastB.end - B_split;
0903.                                     
0904.                                    // swap the minimum A block to the beginning of the rolling A blocks
0905.                                    int minA = blockA.start;
0906.                                    for (int findA = minA + block_size; findA < blockA.end; findA += block_size)
0907.                                        if (comp.compare(array[findA], array[minA]) < 0)
0908.                                            minA = findA;
0909.                                    BlockSwap(array, blockA.start, minA, block_size);
0910.                                     
0911.                                    // swap the first item of the previous A block back with its original value, which is stored in buffer1
0912.                                    T swap = array[blockA.start];
0913.                                    array[blockA.start] = array[indexA];
0914.                                    array[indexA] = swap;
0915.                                    indexA++;
0916.                                     
0917.                                    // locally merge the previous A block with the B values that follow it
0918.                                    // if lastA fits into the external cache we'll use that (with MergeExternal),
0919.                                    // or if the second internal buffer exists we'll use that (with MergeInternal),
0920.                                    // or failing that we'll use a strictly in-place merge algorithm (MergeInPlace)
0921.                                    if (lastA.length() <= cache_size)
0922.                                        MergeExternal(array, lastA, new Range(lastA.end, B_split), comp);
0923.                                    else if (buffer2.length() > 0)
0924.                                        MergeInternal(array, lastA, new Range(lastA.end, B_split), comp, buffer2);
0925.                                    else
0926.                                        MergeInPlace(array, lastA, new Range(lastA.end, B_split), comp);
0927.                                     
0928.                                    if (buffer2.length() > 0 || block_size <= cache_size) {
0929.                                        // copy the previous A block into the cache or buffer2, since that's where we need it to be when we go to merge it anyway
0930.                                        if (block_size <= cache_size)
0931.                                            java.lang.System.arraycopy(array, blockA.start, cache, 0, block_size);
0932.                                        else
0933.                                            BlockSwap(array, blockA.start, buffer2.start, block_size);
0934.                                         
0935.                                        // this is equivalent to rotating, but faster
0936.                                        // the area normally taken up by the A block is either the contents of buffer2, or data we don't need anymore since we memcopied it
0937.                                        // either way, we don't need to retain the order of those items, so instead of rotating we can just block swap B to where it belongs
0938.                                        BlockSwap(array, B_split, blockA.start + block_size - B_remaining, B_remaining);
0939.                                    } else {
0940.                                        // we are unable to use the 'buffer2' trick to speed up the rotation operation since buffer2 doesn't exist, so perform a normal rotation
0941.                                        Rotate(array, blockA.start - B_split, new Range(B_split, blockA.start + block_size), true);
0942.                                    }
0943.                                     
0944.                                    // update the range for the remaining A blocks, and the range remaining from the B block after it was split
0945.                                    lastA.set(blockA.start - B_remaining, blockA.start - B_remaining + block_size);
0946.                                    lastB.set(lastA.end, lastA.end + B_remaining);
0947.                                     
0948.                                    // if there are no more A blocks remaining, this step is finished!
0949.                                    blockA.start += block_size;
0950.                                    if (blockA.length() == 0)
0951.                                        break;
0952.                                     
0953.                                } else if (blockB.length() < block_size) {
0954.                                    // move the last B block, which is unevenly sized, to before the remaining A blocks, by using a rotation
0955.                                    // the cache is disabled here since it might contain the contents of the previous A block
0956.                                    Rotate(array, -blockB.length(), new Range(blockA.start, blockB.end), false);
0957.                                     
0958.                                    lastB.set(blockA.start, blockA.start + blockB.length());
0959.                                    blockA.start += blockB.length();
0960.                                    blockA.end += blockB.length();
0961.                                    blockB.end = blockB.start;
0962.                                } else {
0963.                                    // roll the leftmost A block to the end by swapping it with the next B block
0964.                                    BlockSwap(array, blockA.start, blockB.start, block_size);
0965.                                    lastB.set(blockA.start, blockA.start + block_size);
0966.                                     
0967.                                    blockA.start += block_size;
0968.                                    blockA.end += block_size;
0969.                                    blockB.start += block_size;
0970.                                    blockB.end += block_size;
0971.                                     
0972.                                    if (blockB.end > B.end)
0973.                                        blockB.end = B.end;
0974.                                }
0975.                            }
0976.                        }
0977.                         
0978.                        // merge the last A block with the remaining B values
0979.                        if (lastA.length() <= cache_size)
0980.                            MergeExternal(array, lastA, new Range(lastA.end, B.end), comp);
0981.                        else if (buffer2.length() > 0)
0982.                            MergeInternal(array, lastA, new Range(lastA.end, B.end), comp, buffer2);
0983.                        else
0984.                            MergeInPlace(array, lastA, new Range(lastA.end, B.end), comp);
0985.                    }
0986.                }
0987.                 
0988.                // when we're finished with this merge step we should have the one or two internal buffers left over, where the second buffer is all jumbled up
0989.                // insertion sort the second buffer, then redistribute the buffers back into the array using the opposite process used for creating the buffer
0990.                 
0991.                // while an unstable sort like quick sort could be applied here, in benchmarks it was consistently slightly slower than a simple insertion sort,
0992.                // even for tens of millions of items. this may be because insertion sort is quite fast when the data is already somewhat sorted, like it is here
0993.                InsertionSort(array, buffer2, comp);
0994.                 
0995.                for (pull_index = 0; pull_index < 2; pull_index++) {
0996.                    int unique = pull[pull_index].count * 2;
0997.                    if (pull[pull_index].from > pull[pull_index].to) {
0998.                        // the values were pulled out to the left, so redistribute them back to the right
0999.                        Range buffer = new Range(pull[pull_index].range.start, pull[pull_index].range.start + pull[pull_index].count);
1000.                        while (buffer.length() > 0) {
1001.                            index = FindFirstForward(array, array[buffer.start], new Range(buffer.end, pull[pull_index].range.end), comp, unique);
1002.                            int amount = index - buffer.end;
1003.                            Rotate(array, buffer.length(), new Range(buffer.start, index), true);
1004.                            buffer.start += (amount + 1);
1005.                            buffer.end += amount;
1006.                            unique -= 2;
1007.                        }
1008.                    } else if (pull[pull_index].from < pull[pull_index].to) {
1009.                        // the values were pulled out to the right, so redistribute them back to the left
1010.                        Range buffer = new Range(pull[pull_index].range.end - pull[pull_index].count, pull[pull_index].range.end);
1011.                        while (buffer.length() > 0) {
1012.                            index = FindLastBackward(array, array[buffer.end - 1], new Range(pull[pull_index].range.start, buffer.start), comp, unique);
1013.                            int amount = buffer.start - index;
1014.                            Rotate(array, amount, new Range(index, buffer.end), true);
1015.                            buffer.start -= amount;
1016.                            buffer.end -= (amount + 1);
1017.                            unique -= 2;
1018.                        }
1019.                    }
1020.                }
1021.            }
1022.             
1023.            // double the size of each A and B subarray that will be merged in the next level
1024.            if (!iterator.nextLevel()) break;
1025.        }
1026.    }
1027.}
1028. 
1029.class MergeSorter<t> {
1030.    // n^2 sorting algorithm used to sort tiny chunks of the full array
1031.    void InsertionSort(T array[], Range range, Comparator<t> comp) {
1032.        for (int i = range.start + 1; i < range.end; i++) {
1033.            T temp = array[i];
1034.            int j;
1035.            for (j = i; j > range.start && comp.compare(temp, array[j - 1]) < 0; j--)
1036.                array[j] = array[j - 1];
1037.            array[j] = temp;
1038.        }
1039.    }
1040.     
1041.    // standard merge sort, so we have a baseline for how well WikiSort works
1042.    void SortR(T array[], Range range, Comparator<t> comp, T buffer[]) {
1043.        if (range.length() < 32) {
1044.            // insertion sort
1045.            InsertionSort(array, range, comp);
1046.            return;
1047.        }
1048.         
1049.        int mid = range.start + (range.end - range.start)/2;
1050.        Range A = new Range(range.start, mid);
1051.        Range B = new Range(mid, range.end);
1052.         
1053.        SortR(array, A, comp, buffer);
1054.        SortR(array, B, comp, buffer);
1055.         
1056.        // standard merge operation here (only A is copied to the buffer)
1057.        java.lang.System.arraycopy(array, A.start, buffer, 0, A.length());
1058.        int A_count = 0, B_count = 0, insert = 0;
1059.        while (A_count < A.length() && B_count < B.length()) {
1060.            if (comp.compare(array[A.end + B_count], buffer[A_count]) >= 0) {
1061.                array[A.start + insert] = buffer[A_count];
1062.                A_count++;
1063.            } else {
1064.                array[A.start + insert] = array[A.end + B_count];
1065.                B_count++;
1066.            }
1067.            insert++;
1068.        }
1069.         
1070.        java.lang.System.arraycopy(buffer, A_count, array, A.start + insert, A.length() - A_count);
1071.    }
1072.     
1073.    void Sort(T array[], Comparator<t> comp) {
1074.        @SuppressWarnings("unchecked")
1075.        T[] buffer = (T[]) new Object[array.length];
1076.        SortR(array, new Range(0, array.length), comp, buffer);
1077.    }
1078.     
1079.    public static <t> void sort(T[] array, Comparator<t> comp) {
1080.        new MergeSorter<t>().Sort(array, comp);
1081.    }
1082.}
1083. 
1084.class SortRandom {
1085.    public static Random rand;
1086.    public static int nextInt(int max) {
1087.        // set the seed on the random number generator
1088.        if (rand == null) rand = new Random();
1089.        return rand.nextInt(max);
1090.    }
1091.    public static int nextInt() {
1092.        return nextInt(2147483647);
1093.    }
1094.}
1095. 
1096.class Testing {
1097.    int value(int index, int total) {
1098.        return index;
1099.    }
1100.}
1101. 
1102.class TestingRandom extends Testing {
1103.    int value(int index, int total) {
1104.        return SortRandom.nextInt();
1105.    }
1106.}
1107. 
1108.class TestingRandomFew extends Testing {
1109.    int value(int index, int total) {
1110.        return SortRandom.nextInt(100);
1111.    }
1112.}
1113. 
1114.class TestingMostlyDescending extends Testing {
1115.    int value(int index, int total) {
1116.        return total - index + SortRandom.nextInt(5) - 2;
1117.    }
1118.}
1119. 
1120.class TestingMostlyAscending extends Testing {
1121.    int value(int index, int total) {
1122.        return index + SortRandom.nextInt(5) - 2;
1123.    }
1124.}
1125. 
1126.class TestingAscending extends Testing {
1127.    int value(int index, int total) {
1128.        return index;
1129.    }
1130.}
1131. 
1132.class TestingDescending extends Testing {
1133.    int value(int index, int total) {
1134.        return total - index;
1135.    }
1136.}
1137. 
1138.class TestingEqual extends Testing {
1139.    int value(int index, int total) {
1140.        return 1000;
1141.    }
1142.}
1143. 
1144.class TestingJittered extends Testing {
1145.    int value(int index, int total) {
1146.        return (SortRandom.nextInt(100) <= 90) ? index : (index - 2);
1147.    }
1148.}
1149. 
1150.class TestingMostlyEqual extends Testing {
1151.    int value(int index, int total) {
1152.        return 1000 + SortRandom.nextInt(4);
1153.    }
1154.}
1155. 
1156.// the last 1/5 of the data is random
1157.class TestingAppend extends Testing {
1158.    int value(int index, int total) {
1159.        if (index > total - total/5) return SortRandom.nextInt(total);
1160.        return index;
1161.    }
1162.}
1163. 
1164.class WikiSort {
1165.    static double Seconds() {
1166.        return System.currentTimeMillis()/1000.0;
1167.    }
1168.     
1169.    // make sure the items within the given range are in a stable order
1170.    // if you want to test the correctness of any changes you make to the main WikiSort function,
1171.    // call it from within WikiSort after each step
1172.    static void Verify(Test array[], Range range, TestComparator comp, String msg) {
1173.        for (int index = range.start + 1; index < range.end; index++) {
1174.            // if it's in ascending order then we're good
1175.            // if both values are equal, we need to make sure the index values are ascending
1176.            if (!(comp.compare(array[index - 1], array[index]) < 0 ||
1177.                  (comp.compare(array[index], array[index - 1]) == 0 && array[index].index > array[index - 1].index))) {
1178.                 
1179.                //for (int index2 = range.start; index2 < range.end; index2++)
1180.                //  System.out.println(array[index2].value + " (" + array[index2].index + ")");
1181.                 
1182.                System.out.println("failed with message: " + msg);
1183.                throw new RuntimeException();
1184.            }
1185.        }
1186.    }
1187.     
1188.    public static void main (String[] args) throws java.lang.Exception {
1189.        int max_size = 1500000;
1190.        TestComparator comp = new TestComparator();
1191.        Test[] array1;
1192.        Test[] array2;
1193.        int compares1, compares2, total_compares1 = 0, total_compares2 = 0;
1194.         
1195.        Testing[] test_cases = {
1196.            new TestingRandom(),
1197.            new TestingRandomFew(),
1198.            new TestingMostlyDescending(),
1199.            new TestingMostlyAscending(),
1200.            new TestingAscending(),
1201.            new TestingDescending(),
1202.            new TestingEqual(),
1203.            new TestingJittered(),
1204.            new TestingMostlyEqual(),
1205.            new TestingAppend()
1206.        };
1207.         
1208.        WikiSorter<test> Wiki = new WikiSorter<test>();
1209.        MergeSorter<test> Merge = new MergeSorter<test>();
1210.         
1211.        System.out.println("running test cases...");
1212.        int total = max_size;
1213.        array1 = new Test[total];
1214.        array2 = new Test[total];
1215.         
1216.        for (int test_case = 0; test_case < test_cases.length; test_case++) {
1217.             
1218.            for (int index = 0; index < total; index++) {
1219.                Test item = new Test();
1220.                 
1221.                item.value = test_cases[test_case].value(index, total);
1222.                item.index = index;
1223.                 
1224.                array1[index] = item;
1225.                array2[index] = item;
1226.            }
1227.             
1228.            Wiki.Sort(array1, comp);
1229.            Merge.Sort(array2, comp);
1230.             
1231.            Verify(array1, new Range(0, total), comp, "test case failed");
1232.            for (int index = 0; index < total; index++) {
1233.                if (comp.compare(array1[index], array2[index]) != 0) throw new Exception();
1234.                if (array2[index].index != array1[index].index) throw new Exception();
1235.            }
1236.        }
1237.        System.out.println("passed!");
1238.         
1239.        double total_time = Seconds();
1240.        double total_time1 = 0, total_time2 = 0;
1241.         
1242.        for (total = 0; total < max_size; total += 2048 * 16) {
1243.            array1 = new Test[total];
1244.            array2 = new Test[total];
1245.             
1246.            for (int index = 0; index < total; index++) {
1247.                Test item = new Test();
1248.                 
1249.                item.value = SortRandom.nextInt();
1250.                item.index = index;
1251.                 
1252.                array1[index] = item;
1253.                array2[index] = item;
1254.            }
1255.             
1256.            double time1 = Seconds();
1257.            TestComparator.comparisons = 0;
1258.            Wiki.Sort(array1, comp);
1259.            time1 = Seconds() - time1;
1260.            total_time1 += time1;
1261.            compares1 = TestComparator.comparisons;
1262.            total_compares1 += compares1;
1263.             
1264.            double time2 = Seconds();
1265.            TestComparator.comparisons = 0;
1266.            Merge.Sort(array2, comp);
1267.            time2 = Seconds() - time2;
1268.            total_time2 += time2;
1269.            compares2 = TestComparator.comparisons;
1270.            total_compares2 += compares2;
1271.             
1272.            System.out.format("[%d]\n", total);
1273.             
1274.            if (time1 >= time2)
1275.                System.out.format("WikiSort: %f seconds, MergeSort: %f seconds (%f%% as fast)\n", time1, time2, time2/time1 * 100.0);
1276.            else
1277.                System.out.format("WikiSort: %f seconds, MergeSort: %f seconds (%f%% faster)\n", time1, time2, time2/time1 * 100.0 - 100.0);
1278.             
1279.            if (compares1 <= compares2)
1280.                System.out.format("WikiSort: %d compares, MergeSort: %d compares (%f%% as many)\n", compares1, compares2, compares1 * 100.0/compares2);
1281.            else
1282.                System.out.format("WikiSort: %d compares, MergeSort: %d compares (%f%% more)\n", compares1, compares2, compares1 * 100.0/compares2 - 100.0);
1283.             
1284.            // make sure the arrays are sorted correctly, and that the results were stable
1285.            System.out.println("verifying...");
1286.             
1287.            Verify(array1, new Range(0, total), comp, "testing the final array");
1288.            for (int index = 0; index < total; index++) {
1289.                if (comp.compare(array1[index], array2[index]) != 0) throw new Exception();
1290.                if (array2[index].index != array1[index].index) throw new Exception();
1291.            }
1292.             
1293.            System.out.println("correct!");
1294.        }
1295.         
1296.        total_time = Seconds() - total_time;
1297.        System.out.format("tests completed in %f seconds\n", total_time);
1298.        if (total_time1 >= total_time2)
1299.            System.out.format("WikiSort: %f seconds, MergeSort: %f seconds (%f%% as fast)\n", total_time1, total_time2, total_time2/total_time1 * 100.0);
1300.        else
1301.            System.out.format("WikiSort: %f seconds, MergeSort: %f seconds (%f%% faster)\n", total_time1, total_time2, total_time2/total_time1 * 100.0 - 100.0);
1302.         
1303.        if (total_compares1 <= total_compares2)
1304.            System.out.format("WikiSort: %d compares, MergeSort: %d compares (%f%% as many)\n", total_compares1, total_compares2, total_compares1 * 100.0/total_compares2);
1305.        else
1306.            System.out.format("WikiSort: %d compares, MergeSort: %d compares (%f%% more)\n", total_compares1, total_compares2, total_compares1 * 100.0/total_compares2 - 100.0);
1307.    }
1308.}
1309.            </test></test></test></test></t></t></t></t></t></t></t></t></t></t></t></t></t></t></t></t></t></t></t></t></t></t></t></t></test>
0001.             
0002./***********************************************************
0003. WikiSort (public domain license)
0005.  
0006. to run:
0007. clang -o WikiSort.x WikiSort.c -O3
0008. (or replace 'clang' with 'gcc')
0009. ./WikiSort.x
0010.***********************************************************/
0011. 
0012.#include <stdio.h>
0013.#include <stdlib.h>
0014.#include <stdint.h>
0015.#include <stdarg.h>
0016.#include <string.h>
0017.#include <math.h>
0018.#include <assert.h>
0019.#include <time.h>
0020.#include <limits.h>
0021. 
0022./* record the number of comparisons */
0023./* note that this reduces WikiSort's performance when enabled */
0024.#define PROFILE false
0025. 
0026./* verify that WikiSort is actually correct */
0027./* (this also reduces performance slightly) */
0028.#define VERIFY false
0029. 
0030./* simulate comparisons that have a bit more overhead than just an inlined (int < int) */
0031./* (so we can tell whether reducing the number of comparisons was worth the added complexity) */
0032.#define SLOW_COMPARISONS false
0033. 
0034./* whether to give WikiSort a full-size cache, to see how it performs when given more memory */
0035.#define DYNAMIC_CACHE false
0036. 
0037. 
0038.double Seconds() { return clock() * 1.0/CLOCKS_PER_SEC; }
0039. 
0040./* various #defines for the C code */
0041.#ifndef true
0042.    #define true 1
0043.    #define false 0
0044.    typedef uint8_t bool;
0045.#endif
0046. 
0047.#define Var(name, value)                __typeof__(value) name = value
0048.#define Allocate(type, count)               (type *)malloc((count) * sizeof(type))
0049. 
0050.size_t Min(const size_t a, const size_t b) {
0051.    if (a < b) return a;
0052.    return b;
0053.}
0054. 
0055.size_t Max(const size_t a, const size_t b) {
0056.    if (a > b) return a;
0057.    return b;
0058.}
0059. 
0060. 
0061./* structure to test stable sorting (index will contain its original index in the array, to make sure it doesn't switch places with other items) */
0062.typedef struct {
0063.    size_t value;
0064.#if VERIFY
0065.    size_t index;
0066.#endif
0067.} Test;
0068. 
0069.#if PROFILE
0070.    /* global for testing how many comparisons are performed for each sorting algorithm */
0071.    size_t comparisons;
0072.#endif
0073. 
0074.#if SLOW_COMPARISONS
0075.    #define NOOP_SIZE 50
0076.    size_t noop1[NOOP_SIZE], noop2[NOOP_SIZE];
0077.#endif
0078. 
0079.bool TestCompare(Test item1, Test item2) {
0080.    #if SLOW_COMPARISONS
0081.        /* test slow comparisons by adding some fake overhead */
0082.        /* (in real-world use this might be string comparisons, etc.) */
0083.        size_t index;
0084.        for (index = 0; index < NOOP_SIZE; index++)
0085.            noop1[index] = noop2[index];
0086.    #endif
0087.     
0088.    #if PROFILE
0089.        comparisons++;
0090.    #endif
0091.     
0092.    return (item1.value < item2.value);
0093.}
0094. 
0095.typedef bool (*Comparison)(Test, Test);
0096. 
0097. 
0098. 
0099./* structure to represent ranges within the array */
0100.typedef struct {
0101.    size_t start;
0102.    size_t end;
0103.} Range;
0104. 
0105.size_t Range_length(Range range) { return range.end - range.start; }
0106. 
0107.Range Range_new(const size_t start, const size_t end) {
0108.    Range range;
0109.    range.start = start;
0110.    range.end = end;
0111.    return range;
0112.}
0113. 
0114. 
0115./* toolbox functions used by the sorter */
0116. 
0117./* swap value1 and value2 */
0118.#define Swap(value1, value2) { \
0119.    Var(a, &(value1)); \
0120.    Var(b, &(value2)); \
0121.    \
0122.    Var(c, *a); \
0123.    *a = *b; \
0124.    *b = c; \
0125.}
0126. 
0127./* 63 -> 32, 64 -> 64, etc. */
0128./* this comes from Hacker's Delight */
0129.size_t FloorPowerOfTwo (const size_t value) {
0130.    size_t x = value;
0131.    x = x | (x >> 1);
0132.    x = x | (x >> 2);
0133.    x = x | (x >> 4);
0134.    x = x | (x >> 8);
0135.    x = x | (x >> 16);
0136.#if __LP64__
0137.    x = x | (x >> 32);
0138.#endif
0139.    return x - (x >> 1);
0140.}
0141. 
0142./* find the index of the first value within the range that is equal to array[index] */
0143.size_t BinaryFirst(const Test array[], const Test value, const Range range, const Comparison compare) {
0144.    size_t start = range.start, end = range.end - 1;
0145.    if (range.start >= range.end) return range.start;
0146.    while (start < end) {
0147.        size_t mid = start + (end - start)/2;
0148.        if (compare(array[mid], value))
0149.            start = mid + 1;
0150.        else
0151.            end = mid;
0152.    }
0153.    if (start == range.end - 1 && compare(array[start], value)) start++;
0154.    return start;
0155.}
0156. 
0157./* find the index of the last value within the range that is equal to array[index], plus 1 */
0158.size_t BinaryLast(const Test array[], const Test value, const Range range, const Comparison compare) {
0159.    size_t start = range.start, end = range.end - 1;
0160.    if (range.start >= range.end) return range.end;
0161.    while (start < end) {
0162.        size_t mid = start + (end - start)/2;
0163.        if (!compare(value, array[mid]))
0164.            start = mid + 1;
0165.        else
0166.            end = mid;
0167.    }
0168.    if (start == range.end - 1 && !compare(value, array[start])) start++;
0169.    return start;
0170.}
0171. 
0172./* combine a linear search with a binary search to reduce the number of comparisons in situations */
0173./* where have some idea as to how many unique values there are and where the next value might be */
0174.size_t FindFirstForward(const Test array[], const Test value, const Range range, const Comparison compare, const size_t unique) {
0175.    size_t skip, index;
0176.    if (Range_length(range) == 0) return range.start;
0177.    skip = Max(Range_length(range)/unique, 1);
0178.     
0179.    for (index = range.start + skip; compare(array[index - 1], value); index += skip)
0180.        if (index >= range.end - skip)
0181.            return BinaryFirst(array, value, Range_new(index, range.end), compare);
0182.     
0183.    return BinaryFirst(array, value, Range_new(index - skip, index), compare);
0184.}
0185. 
0186.size_t FindLastForward(const Test array[], const Test value, const Range range, const Comparison compare, const size_t unique) {
0187.    size_t skip, index;
0188.    if (Range_length(range) == 0) return range.start;
0189.    skip = Max(Range_length(range)/unique, 1);
0190.     
0191.    for (index = range.start + skip; !compare(value, array[index - 1]); index += skip)
0192.        if (index >= range.end - skip)
0193.            return BinaryLast(array, value, Range_new(index, range.end), compare);
0194.     
0195.    return BinaryLast(array, value, Range_new(index - skip, index), compare);
0196.}
0197. 
0198.size_t FindFirstBackward(const Test array[], const Test value, const Range range, const Comparison compare, const size_t unique) {
0199.    size_t skip, index;
0200.    if (Range_length(range) == 0) return range.start;
0201.    skip = Max(Range_length(range)/unique, 1);
0202.     
0203.    for (index = range.end - skip; index > range.start && !compare(array[index - 1], value); index -= skip)
0204.        if (index < range.start + skip)
0205.            return BinaryFirst(array, value, Range_new(range.start, index), compare);
0206.     
0207.    return BinaryFirst(array, value, Range_new(index, index + skip), compare);
0208.}
0209. 
0210.size_t FindLastBackward(const Test array[], const Test value, const Range range, const Comparison compare, const size_t unique) {
0211.    size_t skip, index;
0212.    if (Range_length(range) == 0) return range.start;
0213.    skip = Max(Range_length(range)/unique, 1);
0214.     
0215.    for (index = range.end - skip; index > range.start && compare(value, array[index - 1]); index -= skip)
0216.        if (index < range.start + skip)
0217.            return BinaryLast(array, value, Range_new(range.start, index), compare);
0218.     
0219.    return BinaryLast(array, value, Range_new(index, index + skip), compare);
0220.}
0221. 
0222./* n^2 sorting algorithm used to sort tiny chunks of the full array */
0223.void InsertionSort(Test array[], const Range range, const Comparison compare) {
0224.    size_t i, j;
0225.    for (i = range.start + 1; i < range.end; i++) {
0226.        const Test temp = array[i];
0227.        for (j = i; j > range.start && compare(temp, array[j - 1]); j--)
0228.            array[j] = array[j - 1];
0229.        array[j] = temp;
0230.    }
0231.}
0232. 
0233./* reverse a range of values within the array */
0234.void Reverse(Test array[], const Range range) {
0235.    size_t index;
0236.    for (index = Range_length(range)/2; index > 0; index--)
0237.        Swap(array[range.start + index - 1], array[range.end - index]);
0238.}
0239. 
0240./* swap a series of values in the array */
0241.void BlockSwap(Test array[], const size_t start1, const size_t start2, const size_t block_size) {
0242.    size_t index;
0243.    for (index = 0; index < block_size; index++)
0244.        Swap(array[start1 + index], array[start2 + index]);
0245.}
0246. 
0247./* rotate the values in an array ([0 1 2 3] becomes [1 2 3 0] if we rotate by 1) */
0248./* this assumes that 0 <= amount <= range.length() */
0249.void Rotate(Test array[], const size_t amount, const Range range, Test cache[], const size_t cache_size) {
0250.    size_t split; Range range1, range2;
0251.    if (Range_length(range) == 0) return;
0252.     
0253.    split = range.start + amount;
0254.    range1 = Range_new(range.start, split);
0255.    range2 = Range_new(split, range.end);
0256.     
0257.    /* if the smaller of the two ranges fits into the cache, it's *slightly* faster copying it there and shifting the elements over */
0258.    if (Range_length(range1) <= Range_length(range2)) {
0259.        if (Range_length(range1) <= cache_size) {
0260.            memcpy(&cache[0], &array[range1.start], Range_length(range1) * sizeof(array[0]));
0261.            memmove(&array[range1.start], &array[range2.start], Range_length(range2) * sizeof(array[0]));
0262.            memcpy(&array[range1.start + Range_length(range2)], &cache[0], Range_length(range1) * sizeof(array[0]));
0263.            return;
0264.        }
0265.    } else {
0266.        if (Range_length(range2) <= cache_size) {
0267.            memcpy(&cache[0], &array[range2.start], Range_length(range2) * sizeof(array[0]));
0268.            memmove(&array[range2.end - Range_length(range1)], &array[range1.start], Range_length(range1) * sizeof(array[0]));
0269.            memcpy(&array[range1.start], &cache[0], Range_length(range2) * sizeof(array[0]));
0270.            return;
0271.        }
0272.    }
0273.     
0274.    Reverse(array, range1);
0275.    Reverse(array, range2);
0276.    Reverse(array, range);
0277.}
0278. 
0279./* calculate how to scale the index value to the range within the array */
0280./* the bottom-up merge sort only operates on values that are powers of two, */
0281./* so scale down to that power of two, then use a fraction to scale back again */
0282.typedef struct {
0283.    size_t size, power_of_two;
0284.    size_t numerator, decimal;
0285.    size_t denominator, decimal_step, numerator_step;
0286.} WikiIterator;
0287. 
0288.void WikiIterator_begin(WikiIterator *me) {
0289.    me->numerator = me->decimal = 0;
0290.}
0291. 
0292.Range WikiIterator_nextRange(WikiIterator *me) {
0293.    size_t start = me->decimal;
0294.     
0295.    me->decimal += me->decimal_step;
0296.    me->numerator += me->numerator_step;
0297.    if (me->numerator >= me->denominator) {
0298.        me->numerator -= me->denominator;
0299.        me->decimal++;
0300.    }
0301.     
0302.    return Range_new(start, me->decimal);
0303.}
0304. 
0305.bool WikiIterator_finished(WikiIterator *me) {
0306.    return (me->decimal >= me->size);
0307.}
0308. 
0309.bool WikiIterator_nextLevel(WikiIterator *me) {
0310.    me->decimal_step += me->decimal_step;
0311.    me->numerator_step += me->numerator_step;
0312.    if (me->numerator_step >= me->denominator) {
0313.        me->numerator_step -= me->denominator;
0314.        me->decimal_step++;
0315.    }
0316.     
0317.    return (me->decimal_step < me->size);
0318.}
0319. 
0320.size_t WikiIterator_length(WikiIterator *me) {
0321.    return me->decimal_step;
0322.}
0323. 
0324.WikiIterator WikiIterator_new(size_t size2, size_t min_level) {
0325.    WikiIterator me;
0326.    me.size = size2;
0327.    me.power_of_two = FloorPowerOfTwo(me.size);
0328.    me.denominator = me.power_of_two/min_level;
0329.    me.numerator_step = me.size % me.denominator;
0330.    me.decimal_step = me.size/me.denominator;
0331.    WikiIterator_begin(&me);
0332.    return me;
0333.}
0334. 
0335./* merge two ranges from one array and save the results into a different array */
0336.void MergeInto(Test from[], const Range A, const Range B, const Comparison compare, Test into[]) {
0337.    Test *A_index = &from[A.start], *B_index = &from[B.start];
0338.    Test *A_last = &from[A.end], *B_last = &from[B.end];
0339.    Test *insert_index = &into[0];
0340.     
0341.    while (true) {
0342.        if (!compare(*B_index, *A_index)) {
0343.            *insert_index = *A_index;
0344.            A_index++;
0345.            insert_index++;
0346.            if (A_index == A_last) {
0347.                /* copy the remainder of B into the final array */
0348.                memcpy(insert_index, B_index, (B_last - B_index) * sizeof(from[0]));
0349.                break;
0350.            }
0351.        } else {
0352.            *insert_index = *B_index;
0353.            B_index++;
0354.            insert_index++;
0355.            if (B_index == B_last) {
0356.                /* copy the remainder of A into the final array */
0357.                memcpy(insert_index, A_index, (A_last - A_index) * sizeof(from[0]));
0358.                break;
0359.            }
0360.        }
0361.    }
0362.}
0363. 
0364./* merge operation using an external buffer, */
0365.void MergeExternal(Test array[], const Range A, const Range B, const Comparison compare, Test cache[]) {
0366.    /* A fits into the cache, so use that instead of the internal buffer */
0367.    Test *A_index = &cache[0];
0368.    Test *B_index = &array[B.start];
0369.    Test *insert_index = &array[A.start];
0370.    Test *A_last = &cache[Range_length(A)];
0371.    Test *B_last = &array[B.end];
0372.     
0373.    if (Range_length(B) > 0 && Range_length(A) > 0) {
0374.        while (true) {
0375.            if (!compare(*B_index, *A_index)) {
0376.                *insert_index = *A_index;
0377.                A_index++;
0378.                insert_index++;
0379.                if (A_index == A_last) break;
0380.            } else {
0381.                *insert_index = *B_index;
0382.                B_index++;
0383.                insert_index++;
0384.                if (B_index == B_last) break;
0385.            }
0386.        }
0387.    }
0388.     
0389.    /* copy the remainder of A into the final array */
0390.    memcpy(insert_index, A_index, (A_last - A_index) * sizeof(array[0]));
0391.}
0392. 
0393./* merge operation using an internal buffer */
0394.void MergeInternal(Test array[], const Range A, const Range B, const Comparison compare, const Range buffer) {
0395.    /* whenever we find a value to add to the final array, swap it with the value that's already in that spot */
0396.    /* when this algorithm is finished, 'buffer' will contain its original contents, but in a different order */
0397.    size_t A_count = 0, B_count = 0, insert = 0;
0398.     
0399.    if (Range_length(B) > 0 && Range_length(A) > 0) {
0400.        while (true) {
0401.            if (!compare(array[B.start + B_count], array[buffer.start + A_count])) {
0402.                Swap(array[A.start + insert], array[buffer.start + A_count]);
0403.                A_count++;
0404.                insert++;
0405.                if (A_count >= Range_length(A)) break;
0406.            } else {
0407.                Swap(array[A.start + insert], array[B.start + B_count]);
0408.                B_count++;
0409.                insert++;
0410.                if (B_count >= Range_length(B)) break;
0411.            }
0412.        }
0413.    }
0414.     
0415.    /* swap the remainder of A into the final array */
0416.    BlockSwap(array, buffer.start + A_count, A.start + insert, Range_length(A) - A_count);
0417.}
0418. 
0419./* merge operation without a buffer */
0420.void MergeInPlace(Test array[], Range A, Range B, const Comparison compare, Test cache[], const size_t cache_size) {
0421.    if (Range_length(A) == 0 || Range_length(B) == 0) return;
0422.     
0423.    /*
0424.     this just repeatedly binary searches into B and rotates A into position.
0425.     the paper suggests using the 'rotation-based Hwang and Lin algorithm' here,
0426.     but I decided to stick with this because it had better situational performance
0427.      
0428.     (Hwang and Lin is designed for merging subarrays of very different sizes,
0429.     but WikiSort almost always uses subarrays that are roughly the same size)
0430.      
0431.     normally this is incredibly suboptimal, but this function is only called
0432.     when none of the A or B blocks in any subarray contained 2√A unique values,
0433.     which places a hard limit on the number of times this will ACTUALLY need
0434.     to binary search and rotate.
0435.      
0436.     according to my analysis the worst case is √A rotations performed on √A items
0437.     once the constant factors are removed, which ends up being O(n)
0438.      
0439.     again, this is NOT a general-purpose solution – it only works well in this case!
0440.     kind of like how the O(n^2) insertion sort is used in some places
0441.     */
0442.     
0443.    while (true) {
0444.        /* find the first place in B where the first item in A needs to be inserted */
0445.        size_t mid = BinaryFirst(array, array[A.start], B, compare);
0446.         
0447.        /* rotate A into place */
0448.        size_t amount = mid - A.end;
0449.        Rotate(array, Range_length(A), Range_new(A.start, mid), cache, cache_size);
0450.        if (B.end == mid) break;
0451.         
0452.        /* calculate the new A and B ranges */
0453.        B.start = mid;
0454.        A = Range_new(A.start + amount, B.start);
0455.        A.start = BinaryLast(array, array[A.start], A, compare);
0456.        if (Range_length(A) == 0) break;
0457.    }
0458.}
0459. 
0460./* bottom-up merge sort combined with an in-place merge algorithm for O(1) memory use */
0461.void WikiSort(Test array[], const size_t size, const Comparison compare) {
0462.    /* use a small cache to speed up some of the operations */
0463.    #if DYNAMIC_CACHE
0464.        size_t cache_size;
0465.        Test *cache = NULL;
0466.    #else
0467.        /* since the cache size is fixed, it's still O(1) memory! */
0468.        /* just keep in mind that making it too small ruins the point (nothing will fit into it), */
0469.        /* and making it too large also ruins the point (so much for "low memory"!) */
0470.        /* removing the cache entirely still gives 70% of the performance of a standard merge */
0471.        #define CACHE_SIZE 512
0472.        const size_t cache_size = CACHE_SIZE;
0473.        Test cache[CACHE_SIZE];
0474.    #endif
0475.     
0476.    WikiIterator iterator;
0477.     
0478.    /* if the array is of size 0, 1, 2, or 3, just sort them like so: */
0479.    if (size < 4) {
0480.        if (size == 3) {
0481.            /* hard-coded insertion sort */
0482.            if (compare(array[1], array[0])) Swap(array[0], array[1]);
0483.            if (compare(array[2], array[1])) {
0484.                Swap(array[1], array[2]);
0485.                if (compare(array[1], array[0])) Swap(array[0], array[1]);
0486.            }
0487.        } else if (size == 2) {
0488.            /* swap the items if they're out of order */
0489.            if (compare(array[1], array[0])) Swap(array[0], array[1]);
0490.        }
0491.         
0492.        return;
0493.    }
0494.     
0495.    /* sort groups of 4-8 items at a time using an unstable sorting network, */
0496.    /* but keep track of the original item orders to force it to be stable */
0497.    /* http://pages.ripco.net/~jgamble/nw.html */
0498.    iterator = WikiIterator_new(size, 4);
0499.    WikiIterator_begin(&iterator);
0500.    while (!WikiIterator_finished(&iterator)) {
0501.        uint8_t order[] = { 0, 1, 2, 3, 4, 5, 6, 7 };
0502.        Range range = WikiIterator_nextRange(&iterator);
0503.         
0504.        #define SWAP(x, y) if (compare(array[range.start + y], array[range.start + x]) || \
0505.                                (order[x] > order[y] && !compare(array[range.start + x], array[range.start + y]))) { \
0506.                                Swap(array[range.start + x], array[range.start + y]); Swap(order[x], order[y]); }
0507.         
0508.        if (Range_length(range) == 8) {
0509.            SWAP(0, 1); SWAP(2, 3); SWAP(4, 5); SWAP(6, 7);
0510.            SWAP(0, 2); SWAP(1, 3); SWAP(4, 6); SWAP(5, 7);
0511.            SWAP(1, 2); SWAP(5, 6); SWAP(0, 4); SWAP(3, 7);
0512.            SWAP(1, 5); SWAP(2, 6);
0513.            SWAP(1, 4); SWAP(3, 6);
0514.            SWAP(2, 4); SWAP(3, 5);
0515.            SWAP(3, 4);
0516.             
0517.        } else if (Range_length(range) == 7) {
0518.            SWAP(1, 2); SWAP(3, 4); SWAP(5, 6);
0519.            SWAP(0, 2); SWAP(3, 5); SWAP(4, 6);
0520.            SWAP(0, 1); SWAP(4, 5); SWAP(2, 6);
0521.            SWAP(0, 4); SWAP(1, 5);
0522.            SWAP(0, 3); SWAP(2, 5);
0523.            SWAP(1, 3); SWAP(2, 4);
0524.            SWAP(2, 3);
0525.             
0526.        } else if (Range_length(range) == 6) {
0527.            SWAP(1, 2); SWAP(4, 5);
0528.            SWAP(0, 2); SWAP(3, 5);
0529.            SWAP(0, 1); SWAP(3, 4); SWAP(2, 5);
0530.            SWAP(0, 3); SWAP(1, 4);
0531.            SWAP(2, 4); SWAP(1, 3);
0532.            SWAP(2, 3);
0533.             
0534.        } else if (Range_length(range) == 5) {
0535.            SWAP(0, 1); SWAP(3, 4);
0536.            SWAP(2, 4);
0537.            SWAP(2, 3); SWAP(1, 4);
0538.            SWAP(0, 3);
0539.            SWAP(0, 2); SWAP(1, 3);
0540.            SWAP(1, 2);
0541.             
0542.        } else if (Range_length(range) == 4) {
0543.            SWAP(0, 1); SWAP(2, 3);
0544.            SWAP(0, 2); SWAP(1, 3);
0545.            SWAP(1, 2);
0546.        }
0547.    }
0548.    if (size < 8) return;
0549.     
0550.    #if DYNAMIC_CACHE
0551.        /* good choices for the cache size are: */
0552.        /* (size + 1)/2 – turns into a full-speed standard merge sort since everything fits into the cache */
0553.        cache_size = (size + 1)/2;
0554.        cache = (Test *)malloc(cache_size * sizeof(array[0]));
0555.         
0556.        if (!cache) {
0557.            /* sqrt((size + 1)/2) + 1 – this will be the size of the A blocks at the largest level of merges, */
0558.            /* so a buffer of this size would allow it to skip using internal or in-place merges for anything */
0559.            cache_size = sqrt(cache_size) + 1;
0560.            cache = (Test *)malloc(cache_size * sizeof(array[0]));
0561.             
0562.            if (!cache) {
0563.                /* 512 – chosen from careful testing as a good balance between fixed-size memory use and run time */
0564.                if (cache_size > 512) {
0565.                    cache_size = 512;
0566.                    cache = (Test *)malloc(cache_size * sizeof(array[0]));
0567.                }
0568.                 
0569.                /* 0 – if the system simply cannot allocate any extra memory whatsoever, no memory works just fine */
0570.                if (!cache) cache_size = 0;
0571.            }
0572.        }
0573.    #endif
0574.     
0575.    /* then merge sort the higher levels, which can be 8-15, 16-31, 32-63, 64-127, etc. */
0576.    while (true) {
0577.         
0578.        /* if every A and B block will fit into the cache, use a special branch specifically for merging with the cache */
0579.        /* (we use < rather than <= since the block size might be one more than iterator.length()) */
0580.        if (WikiIterator_length(&iterator) < cache_size) {
0581.             
0582.            /* if four subarrays fit into the cache, it's faster to merge both pairs of subarrays into the cache, */
0583.            /* then merge the two merged subarrays from the cache back into the original array */
0584.            if ((WikiIterator_length(&iterator) + 1) * 4 <= cache_size && WikiIterator_length(&iterator) * 4 <= size) {
0585.                WikiIterator_begin(&iterator);
0586.                while (!WikiIterator_finished(&iterator)) {
0587.                    /* merge A1 and B1 into the cache */
0588.                    Range A1, B1, A2, B2, A3, B3;
0589.                    A1 = WikiIterator_nextRange(&iterator);
0590.                    B1 = WikiIterator_nextRange(&iterator);
0591.                    A2 = WikiIterator_nextRange(&iterator);
0592.                    B2 = WikiIterator_nextRange(&iterator);
0593.                     
0594.                    if (compare(array[B1.end - 1], array[A1.start])) {
0595.                        /* the two ranges are in reverse order, so copy them in reverse order into the cache */
0596.                        memcpy(&cache[Range_length(B1)], &array[A1.start], Range_length(A1) * sizeof(array[0]));
0597.                        memcpy(&cache[0], &array[B1.start], Range_length(B1) * sizeof(array[0]));
0598.                    } else if (compare(array[B1.start], array[A1.end - 1])) {
0599.                        /* these two ranges weren't already in order, so merge them into the cache */
0600.                        MergeInto(array, A1, B1, compare, &cache[0]);
0601.                    } else {
0602.                        /* if A1, B1, A2, and B2 are all in order, skip doing anything else */
0603.                        if (!compare(array[B2.start], array[A2.end - 1]) && !compare(array[A2.start], array[B1.end - 1])) continue;
0604.                         
0605.                        /* copy A1 and B1 into the cache in the same order */
0606.                        memcpy(&cache[0], &array[A1.start], Range_length(A1) * sizeof(array[0]));
0607.                        memcpy(&cache[Range_length(A1)], &array[B1.start], Range_length(B1) * sizeof(array[0]));
0608.                    }
0609.                    A1 = Range_new(A1.start, B1.end);
0610.                     
0611.                    /* merge A2 and B2 into the cache */
0612.                    if (compare(array[B2.end - 1], array[A2.start])) {
0613.                        /* the two ranges are in reverse order, so copy them in reverse order into the cache */
0614.                        memcpy(&cache[Range_length(A1) + Range_length(B2)], &array[A2.start], Range_length(A2) * sizeof(array[0]));
0615.                        memcpy(&cache[Range_length(A1)], &array[B2.start], Range_length(B2) * sizeof(array[0]));
0616.                    } else if (compare(array[B2.start], array[A2.end - 1])) {
0617.                        /* these two ranges weren't already in order, so merge them into the cache */
0618.                        MergeInto(array, A2, B2, compare, &cache[Range_length(A1)]);
0619.                    } else {
0620.                        /* copy A2 and B2 into the cache in the same order */
0621.                        memcpy(&cache[Range_length(A1)], &array[A2.start], Range_length(A2) * sizeof(array[0]));
0622.                        memcpy(&cache[Range_length(A1) + Range_length(A2)], &array[B2.start], Range_length(B2) * sizeof(array[0]));
0623.                    }
0624.                    A2 = Range_new(A2.start, B2.end);
0625.                     
0626.                    /* merge A1 and A2 from the cache into the array */
0627.                    A3 = Range_new(0, Range_length(A1));
0628.                    B3 = Range_new(Range_length(A1), Range_length(A1) + Range_length(A2));
0629.                     
0630.                    if (compare(cache[B3.end - 1], cache[A3.start])) {
0631.                        /* the two ranges are in reverse order, so copy them in reverse order into the array */
0632.                        memcpy(&array[A1.start + Range_length(A2)], &cache[A3.start], Range_length(A3) * sizeof(array[0]));
0633.                        memcpy(&array[A1.start], &cache[B3.start], Range_length(B3) * sizeof(array[0]));
0634.                    } else if (compare(cache[B3.start], cache[A3.end - 1])) {
0635.                        /* these two ranges weren't already in order, so merge them back into the array */
0636.                        MergeInto(cache, A3, B3, compare, &array[A1.start]);
0637.                    } else {
0638.                        /* copy A3 and B3 into the array in the same order */
0639.                        memcpy(&array[A1.start], &cache[A3.start], Range_length(A3) * sizeof(array[0]));
0640.                        memcpy(&array[A1.start + Range_length(A1)], &cache[B3.start], Range_length(B3) * sizeof(array[0]));
0641.                    }
0642.                }
0643.                 
0644.                /* we merged two levels at the same time, so we're done with this level already */
0645.                /* (iterator.nextLevel() is called again at the bottom of this outer merge loop) */
0646.                WikiIterator_nextLevel(&iterator);
0647.                 
0648.            } else {
0649.                WikiIterator_begin(&iterator);
0650.                while (!WikiIterator_finished(&iterator)) {
0651.                    Range A = WikiIterator_nextRange(&iterator);
0652.                    Range B = WikiIterator_nextRange(&iterator);
0653.                     
0654.                    if (compare(array[B.end - 1], array[A.start])) {
0655.                        /* the two ranges are in reverse order, so a simple rotation should fix it */
0656.                        Rotate(array, Range_length(A), Range_new(A.start, B.end), cache, cache_size);
0657.                    } else if (compare(array[B.start], array[A.end - 1])) {
0658.                        /* these two ranges weren't already in order, so we'll need to merge them! */
0659.                        memcpy(&cache[0], &array[A.start], Range_length(A) * sizeof(array[0]));
0660.                        MergeExternal(array, A, B, compare, cache);
0661.                    }
0662.                }
0663.            }
0664.        } else {
0665.            /* this is where the in-place merge logic starts!
0666.             1. pull out two internal buffers each containing √A unique values
0667.                1a. adjust block_size and buffer_size if we couldn't find enough unique values
0668.             2. loop over the A and B subarrays within this level of the merge sort
0669.             3. break A and B into blocks of size 'block_size'
0670.             4. "tag" each of the A blocks with values from the first internal buffer
0671.             5. roll the A blocks through the B blocks and drop/rotate them where they belong
0672.             6. merge each A block with any B values that follow, using the cache or the second internal buffer
0673.             7. sort the second internal buffer if it exists
0674.             8. redistribute the two internal buffers back into the array */
0675.             
0676.            size_t block_size = sqrt(WikiIterator_length(&iterator));
0677.            size_t buffer_size = WikiIterator_length(&iterator)/block_size + 1;
0678.             
0679.            /* as an optimization, we really only need to pull out the internal buffers once for each level of merges */
0680.            /* after that we can reuse the same buffers over and over, then redistribute it when we're finished with this level */
0681.            Range buffer1, buffer2, A, B; bool find_separately;
0682.            size_t index, last, count, find, start, pull_index = 0;
0683.            struct { size_t from, to, count; Range range; } pull[2];
0684.            pull[0].from = pull[0].to = pull[0].count = 0; pull[0].range = Range_new(0, 0);
0685.            pull[1].from = pull[1].to = pull[1].count = 0; pull[1].range = Range_new(0, 0);
0686.             
0687.            buffer1 = Range_new(0, 0);
0688.            buffer2 = Range_new(0, 0);
0689.             
0690.            /* find two internal buffers of size 'buffer_size' each */
0691.            find = buffer_size + buffer_size;
0692.            find_separately = false;
0693.             
0694.            if (block_size <= cache_size) {
0695.                /* if every A block fits into the cache then we won't need the second internal buffer, */
0696.                /* so we really only need to find 'buffer_size' unique values */
0697.                find = buffer_size;
0698.            } else if (find > WikiIterator_length(&iterator)) {
0699.                /* we can't fit both buffers into the same A or B subarray, so find two buffers separately */
0700.                find = buffer_size;
0701.                find_separately = true;
0702.            }
0703.             
0704.            /* we need to find either a single contiguous space containing 2√A unique values (which will be split up into two buffers of size √A each), */
0705.            /* or we need to find one buffer of < 2√A unique values, and a second buffer of √A unique values, */
0706.            /* OR if we couldn't find that many unique values, we need the largest possible buffer we can get */
0707.             
0708.            /* in the case where it couldn't find a single buffer of at least √A unique values, */
0709.            /* all of the Merge steps must be replaced by a different merge algorithm (MergeInPlace) */
0710.            WikiIterator_begin(&iterator);
0711.            while (!WikiIterator_finished(&iterator)) {
0712.                A = WikiIterator_nextRange(&iterator);
0713.                B = WikiIterator_nextRange(&iterator);
0714.                 
0715.                /* just store information about where the values will be pulled from and to, */
0716.                /* as well as how many values there are, to create the two internal buffers */
0717.                #define PULL(_to) \
0718.                    pull[pull_index].range = Range_new(A.start, B.end); \
0719.                    pull[pull_index].count = count; \
0720.                    pull[pull_index].from = index; \
0721.                    pull[pull_index].to = _to
0722.                 
0723.                /* check A for the number of unique values we need to fill an internal buffer */
0724.                /* these values will be pulled out to the start of A */
0725.                for (last = A.start, count = 1; count < find; last = index, count++) {
0726.                    index = FindLastForward(array, array[last], Range_new(last + 1, A.end), compare, find - count);
0727.                    if (index == A.end) break;
0728.                }
0729.                index = last;
0730.                 
0731.                if (count >= buffer_size) {
0732.                    /* keep track of the range within the array where we'll need to "pull out" these values to create the internal buffer */
0733.                    PULL(A.start);
0734.                    pull_index = 1;
0735.                     
0736.                    if (count == buffer_size + buffer_size) {
0737.                        /* we were able to find a single contiguous section containing 2√A unique values, */
0738.                        /* so this section can be used to contain both of the internal buffers we'll need */
0739.                        buffer1 = Range_new(A.start, A.start + buffer_size);
0740.                        buffer2 = Range_new(A.start + buffer_size, A.start + count);
0741.                        break;
0742.                    } else if (find == buffer_size + buffer_size) {
0743.                        /* we found a buffer that contains at least √A unique values, but did not contain the full 2√A unique values, */
0744.                        /* so we still need to find a second separate buffer of at least √A unique values */
0745.                        buffer1 = Range_new(A.start, A.start + count);
0746.                        find = buffer_size;
0747.                    } else if (block_size <= cache_size) {
0748.                        /* we found the first and only internal buffer that we need, so we're done! */
0749.                        buffer1 = Range_new(A.start, A.start + count);
0750.                        break;
0751.                    } else if (find_separately) {
0752.                        /* found one buffer, but now find the other one */
0753.                        buffer1 = Range_new(A.start, A.start + count);
0754.                        find_separately = false;
0755.                    } else {
0756.                        /* we found a second buffer in an 'A' subarray containing √A unique values, so we're done! */
0757.                        buffer2 = Range_new(A.start, A.start + count);
0758.                        break;
0759.                    }
0760.                } else if (pull_index == 0 && count > Range_length(buffer1)) {
0761.                    /* keep track of the largest buffer we were able to find */
0762.                    buffer1 = Range_new(A.start, A.start + count);
0763.                    PULL(A.start);
0764.                }
0765.                 
0766.                /* check B for the number of unique values we need to fill an internal buffer */
0767.                /* these values will be pulled out to the end of B */
0768.                for (last = B.end - 1, count = 1; count < find; last = index - 1, count++) {
0769.                    index = FindFirstBackward(array, array[last], Range_new(B.start, last), compare, find - count);
0770.                    if (index == B.start) break;
0771.                }
0772.                index = last;
0773.                 
0774.                if (count >= buffer_size) {
0775.                    /* keep track of the range within the array where we'll need to "pull out" these values to create the internal buffer */
0776.                    PULL(B.end);
0777.                    pull_index = 1;
0778.                     
0779.                    if (count == buffer_size + buffer_size) {
0780.                        /* we were able to find a single contiguous section containing 2√A unique values, */
0781.                        /* so this section can be used to contain both of the internal buffers we'll need */
0782.                        buffer1 = Range_new(B.end - count, B.end - buffer_size);
0783.                        buffer2 = Range_new(B.end - buffer_size, B.end);
0784.                        break;
0785.                    } else if (find == buffer_size + buffer_size) {
0786.                        /* we found a buffer that contains at least √A unique values, but did not contain the full 2√A unique values, */
0787.                        /* so we still need to find a second separate buffer of at least √A unique values */
0788.                        buffer1 = Range_new(B.end - count, B.end);
0789.                        find = buffer_size;
0790.                    } else if (block_size <= cache_size) {
0791.                        /* we found the first and only internal buffer that we need, so we're done! */
0792.                        buffer1 = Range_new(B.end - count, B.end);
0793.                        break;
0794.                    } else if (find_separately) {
0795.                        /* found one buffer, but now find the other one */
0796.                        buffer1 = Range_new(B.end - count, B.end);
0797.                        find_separately = false;
0798.                    } else {
0799.                        /* buffer2 will be pulled out from a 'B' subarray, so if the first buffer was pulled out from the corresponding 'A' subarray, */
0800.                        /* we need to adjust the end point for that A subarray so it knows to stop redistributing its values before reaching buffer2 */
0801.                        if (pull[0].range.start == A.start) pull[0].range.end -= pull[1].count;
0802.                         
0803.                        /* we found a second buffer in an 'B' subarray containing √A unique values, so we're done! */
0804.                        buffer2 = Range_new(B.end - count, B.end);
0805.                        break;
0806.                    }
0807.                } else if (pull_index == 0 && count > Range_length(buffer1)) {
0808.                    /* keep track of the largest buffer we were able to find */
0809.                    buffer1 = Range_new(B.end - count, B.end);
0810.                    PULL(B.end);
0811.                }
0812.            }
0813.             
0814.            /* pull out the two ranges so we can use them as internal buffers */
0815.            for (pull_index = 0; pull_index < 2; pull_index++) {
0816.                Range range;
0817.                size_t length = pull[pull_index].count;
0818.                 
0819.                if (pull[pull_index].to < pull[pull_index].from) {
0820.                    /* we're pulling the values out to the left, which means the start of an A subarray */
0821.                    index = pull[pull_index].from;
0822.                    for (count = 1; count < length; count++) {
0823.                        index = FindFirstBackward(array, array[index - 1], Range_new(pull[pull_index].to, pull[pull_index].from - (count - 1)), compare, length - count);
0824.                        range = Range_new(index + 1, pull[pull_index].from + 1);
0825.                        Rotate(array, Range_length(range) - count, range, cache, cache_size);
0826.                        pull[pull_index].from = index + count;
0827.                    }
0828.                } else if (pull[pull_index].to > pull[pull_index].from) {
0829.                    /* we're pulling values out to the right, which means the end of a B subarray */
0830.                    index = pull[pull_index].from + 1;
0831.                    for (count = 1; count < length; count++) {
0832.                        index = FindLastForward(array, array[index], Range_new(index, pull[pull_index].to), compare, length - count);
0833.                        range = Range_new(pull[pull_index].from, index - 1);
0834.                        Rotate(array, count, range, cache, cache_size);
0835.                        pull[pull_index].from = index - 1 - count;
0836.                    }
0837.                }
0838.            }
0839.             
0840.            /* adjust block_size and buffer_size based on the values we were able to pull out */
0841.            buffer_size = Range_length(buffer1);
0842.            block_size = WikiIterator_length(&iterator)/buffer_size + 1;
0843.             
0844.            /* the first buffer NEEDS to be large enough to tag each of the evenly sized A blocks, */
0845.            /* so this was originally here to test the math for adjusting block_size above */
0846.            /* assert((WikiIterator_length(&iterator) + 1)/block_size <= buffer_size); */
0847.             
0848.            /* now that the two internal buffers have been created, it's time to merge each A+B combination at this level of the merge sort! */
0849.            WikiIterator_begin(&iterator);
0850.            while (!WikiIterator_finished(&iterator)) {
0851.                A = WikiIterator_nextRange(&iterator);
0852.                B = WikiIterator_nextRange(&iterator);
0853.                 
0854.                /* remove any parts of A or B that are being used by the internal buffers */
0855.                start = A.start;
0856.                if (start == pull[0].range.start) {
0857.                    if (pull[0].from > pull[0].to) {
0858.                        A.start += pull[0].count;
0859.                         
0860.                        /* if the internal buffer takes up the entire A or B subarray, then there's nothing to merge */
0861.                        /* this only happens for very small subarrays, like √4 = 2, 2 * (2 internal buffers) = 4, */
0862.                        /* which also only happens when cache_size is small or 0 since it'd otherwise use MergeExternal */
0863.                        if (Range_length(A) == 0) continue;
0864.                    } else if (pull[0].from < pull[0].to) {
0865.                        B.end -= pull[0].count;
0866.                        if (Range_length(B) == 0) continue;
0867.                    }
0868.                }
0869.                if (start == pull[1].range.start) {
0870.                    if (pull[1].from > pull[1].to) {
0871.                        A.start += pull[1].count;
0872.                        if (Range_length(A) == 0) continue;
0873.                    } else if (pull[1].from < pull[1].to) {
0874.                        B.end -= pull[1].count;
0875.                        if (Range_length(B) == 0) continue;
0876.                    }
0877.                }
0878.                 
0879.                if (compare(array[B.end - 1], array[A.start])) {
0880.                    /* the two ranges are in reverse order, so a simple rotation should fix it */
0881.                    Rotate(array, Range_length(A), Range_new(A.start, B.end), cache, cache_size);
0882.                } else if (compare(array[A.end], array[A.end - 1])) {
0883.                    /* these two ranges weren't already in order, so we'll need to merge them! */
0884.                    Range blockA, firstA, lastA, lastB, blockB;
0885.                    size_t indexA, findA;
0886.                     
0887.                    /* break the remainder of A into blocks. firstA is the uneven-sized first A block */
0888.                    blockA = Range_new(A.start, A.end);
0889.                    firstA = Range_new(A.start, A.start + Range_length(blockA) % block_size);
0890.                     
0891.                    /* swap the first value of each A block with the value in buffer1 */
0892.                    for (indexA = buffer1.start, index = firstA.end; index < blockA.end; indexA++, index += block_size)
0893.                        Swap(array[indexA], array[index]);
0894.                     
0895.                    /* start rolling the A blocks through the B blocks! */
0896.                    /* whenever we leave an A block behind, we'll need to merge the previous A block with any B blocks that follow it, so track that information as well */
0897.                    lastA = firstA;
0898.                    lastB = Range_new(0, 0);
0899.                    blockB = Range_new(B.start, B.start + Min(block_size, Range_length(B)));
0900.                    blockA.start += Range_length(firstA);
0901.                    indexA = buffer1.start;
0902.                     
0903.                    /* if the first unevenly sized A block fits into the cache, copy it there for when we go to Merge it */
0904.                    /* otherwise, if the second buffer is available, block swap the contents into that */
0905.                    if (Range_length(lastA) <= cache_size)
0906.                        memcpy(&cache[0], &array[lastA.start], Range_length(lastA) * sizeof(array[0]));
0907.                    else if (Range_length(buffer2) > 0)
0908.                        BlockSwap(array, lastA.start, buffer2.start, Range_length(lastA));
0909.                     
0910.                    if (Range_length(blockA) > 0) {
0911.                        while (true) {
0912.                            /* if there's a previous B block and the first value of the minimum A block is <= the last value of the previous B block, */
0913.                            /* then drop that minimum A block behind. or if there are no B blocks left then keep dropping the remaining A blocks. */
0914.                            if ((Range_length(lastB) > 0 && !compare(array[lastB.end - 1], array[indexA])) || Range_length(blockB) == 0) {
0915.                                /* figure out where to split the previous B block, and rotate it at the split */
0916.                                size_t B_split = BinaryFirst(array, array[indexA], lastB, compare);
0917.                                size_t B_remaining = lastB.end - B_split;
0918.                                 
0919.                                /* swap the minimum A block to the beginning of the rolling A blocks */
0920.                                size_t minA = blockA.start;
0921.                                for (findA = minA + block_size; findA < blockA.end; findA += block_size)
0922.                                    if (compare(array[findA], array[minA]))
0923.                                        minA = findA;
0924.                                BlockSwap(array, blockA.start, minA, block_size);
0925.                                 
0926.                                /* swap the first item of the previous A block back with its original value, which is stored in buffer1 */
0927.                                Swap(array[blockA.start], array[indexA]);
0928.                                indexA++;
0929.                                 
0930.                                /*
0931.                                 locally merge the previous A block with the B values that follow it
0932.                                 if lastA fits into the external cache we'll use that (with MergeExternal),
0933.                                 or if the second internal buffer exists we'll use that (with MergeInternal),
0934.                                 or failing that we'll use a strictly in-place merge algorithm (MergeInPlace)
0935.                                 */
0936.                                if (Range_length(lastA) <= cache_size)
0937.                                    MergeExternal(array, lastA, Range_new(lastA.end, B_split), compare, cache);
0938.                                else if (Range_length(buffer2) > 0)
0939.                                    MergeInternal(array, lastA, Range_new(lastA.end, B_split), compare, buffer2);
0940.                                else
0941.                                    MergeInPlace(array, lastA, Range_new(lastA.end, B_split), compare, cache, cache_size);
0942.                                 
0943.                                if (Range_length(buffer2) > 0 || block_size <= cache_size) {
0944.                                    /* copy the previous A block into the cache or buffer2, since that's where we need it to be when we go to merge it anyway */
0945.                                    if (block_size <= cache_size)
0946.                                        memcpy(&cache[0], &array[blockA.start], block_size * sizeof(array[0]));
0947.                                    else
0948.                                        BlockSwap(array, blockA.start, buffer2.start, block_size);
0949.                                     
0950.                                    /* this is equivalent to rotating, but faster */
0951.                                    /* the area normally taken up by the A block is either the contents of buffer2, or data we don't need anymore since we memcopied it */
0952.                                    /* either way, we don't need to retain the order of those items, so instead of rotating we can just block swap B to where it belongs */
0953.                                    BlockSwap(array, B_split, blockA.start + block_size - B_remaining, B_remaining);
0954.                                } else {
0955.                                    /* we are unable to use the 'buffer2' trick to speed up the rotation operation since buffer2 doesn't exist, so perform a normal rotation */
0956.                                    Rotate(array, blockA.start - B_split, Range_new(B_split, blockA.start + block_size), cache, cache_size);
0957.                                }
0958.                                 
0959.                                /* update the range for the remaining A blocks, and the range remaining from the B block after it was split */
0960.                                lastA = Range_new(blockA.start - B_remaining, blockA.start - B_remaining + block_size);
0961.                                lastB = Range_new(lastA.end, lastA.end + B_remaining);
0962.                                 
0963.                                /* if there are no more A blocks remaining, this step is finished! */
0964.                                blockA.start += block_size;
0965.                                if (Range_length(blockA) == 0)
0966.                                    break;
0967.                                 
0968.                            } else if (Range_length(blockB) < block_size) {
0969.                                /* move the last B block, which is unevenly sized, to before the remaining A blocks, by using a rotation */
0970.                                /* the cache is disabled here since it might contain the contents of the previous A block */
0971.                                Rotate(array, blockB.start - blockA.start, Range_new(blockA.start, blockB.end), cache, 0);
0972.                                 
0973.                                lastB = Range_new(blockA.start, blockA.start + Range_length(blockB));
0974.                                blockA.start += Range_length(blockB);
0975.                                blockA.end += Range_length(blockB);
0976.                                blockB.end = blockB.start;
0977.                            } else {
0978.                                /* roll the leftmost A block to the end by swapping it with the next B block */
0979.                                BlockSwap(array, blockA.start, blockB.start, block_size);
0980.                                lastB = Range_new(blockA.start, blockA.start + block_size);
0981.                                 
0982.                                blockA.start += block_size;
0983.                                blockA.end += block_size;
0984.                                blockB.start += block_size;
0985.                                 
0986.                                if (blockB.end > B.end - block_size) blockB.end = B.end;
0987.                                else blockB.end += block_size;
0988.                            }
0989.                        }
0990.                    }
0991.                     
0992.                    /* merge the last A block with the remaining B values */
0993.                    if (Range_length(lastA) <= cache_size)
0994.                        MergeExternal(array, lastA, Range_new(lastA.end, B.end), compare, cache);
0995.                    else if (Range_length(buffer2) > 0)
0996.                        MergeInternal(array, lastA, Range_new(lastA.end, B.end), compare, buffer2);
0997.                    else
0998.                        MergeInPlace(array, lastA, Range_new(lastA.end, B.end), compare, cache, cache_size);
0999.                }
1000.            }
1001.             
1002.            /* when we're finished with this merge step we should have the one or two internal buffers left over, where the second buffer is all jumbled up */
1003.            /* insertion sort the second buffer, then redistribute the buffers back into the array using the opposite process used for creating the buffer */
1004.             
1005.            /* while an unstable sort like quicksort could be applied here, in benchmarks it was consistently slightly slower than a simple insertion sort, */
1006.            /* even for tens of millions of items. this may be because insertion sort is quite fast when the data is already somewhat sorted, like it is here */
1007.            InsertionSort(array, buffer2, compare);
1008.             
1009.            for (pull_index = 0; pull_index < 2; pull_index++) {
1010.                size_t amount, unique = pull[pull_index].count * 2;
1011.                if (pull[pull_index].from > pull[pull_index].to) {
1012.                    /* the values were pulled out to the left, so redistribute them back to the right */
1013.                    Range buffer = Range_new(pull[pull_index].range.start, pull[pull_index].range.start + pull[pull_index].count);
1014.                    while (Range_length(buffer) > 0) {
1015.                        index = FindFirstForward(array, array[buffer.start], Range_new(buffer.end, pull[pull_index].range.end), compare, unique);
1016.                        amount = index - buffer.end;
1017.                        Rotate(array, Range_length(buffer), Range_new(buffer.start, index), cache, cache_size);
1018.                        buffer.start += (amount + 1);
1019.                        buffer.end += amount;
1020.                        unique -= 2;
1021.                    }
1022.                } else if (pull[pull_index].from < pull[pull_index].to) {
1023.                    /* the values were pulled out to the right, so redistribute them back to the left */
1024.                    Range buffer = Range_new(pull[pull_index].range.end - pull[pull_index].count, pull[pull_index].range.end);
1025.                    while (Range_length(buffer) > 0) {
1026.                        index = FindLastBackward(array, array[buffer.end - 1], Range_new(pull[pull_index].range.start, buffer.start), compare, unique);
1027.                        amount = buffer.start - index;
1028.                        Rotate(array, amount, Range_new(index, buffer.end), cache, cache_size);
1029.                        buffer.start -= amount;
1030.                        buffer.end -= (amount + 1);
1031.                        unique -= 2;
1032.                    }
1033.                }
1034.            }
1035.        }
1036.         
1037.        /* double the size of each A and B subarray that will be merged in the next level */
1038.        if (!WikiIterator_nextLevel(&iterator)) break;
1039.    }
1040.     
1041.    #if DYNAMIC_CACHE
1042.        if (cache) free(cache);
1043.    #endif
1044.     
1045.    #undef CACHE_SIZE
1046.}
1047. 
1048. 
1049. 
1050. 
1051./* standard merge sort, so we have a baseline for how well WikiSort works */
1052.void MergeSortR(Test array[], const Range range, const Comparison compare, Test buffer[]) {
1053.    size_t mid, A_count = 0, B_count = 0, insert = 0;
1054.    Range A, B;
1055.     
1056.    if (Range_length(range) < 32) {
1057.        InsertionSort(array, range, compare);
1058.        return;
1059.    }
1060.     
1061.    mid = range.start + (range.end - range.start)/2;
1062.    A = Range_new(range.start, mid);
1063.    B = Range_new(mid, range.end);
1064.     
1065.    MergeSortR(array, A, compare, buffer);
1066.    MergeSortR(array, B, compare, buffer);
1067.     
1068.    /* standard merge operation here (only A is copied to the buffer, and only the parts that weren't already where they should be) */
1069.    A = Range_new(BinaryLast(array, array[B.start], A, compare), A.end);
1070.    memcpy(&buffer[0], &array[A.start], Range_length(A) * sizeof(array[0]));
1071.    while (A_count < Range_length(A) && B_count < Range_length(B)) {
1072.        if (!compare(array[A.end + B_count], buffer[A_count])) {
1073.            array[A.start + insert] = buffer[A_count];
1074.            A_count++;
1075.        } else {
1076.            array[A.start + insert] = array[A.end + B_count];
1077.            B_count++;
1078.        }
1079.        insert++;
1080.    }
1081.     
1082.    memcpy(&array[A.start + insert], &buffer[A_count], (Range_length(A) - A_count) * sizeof(array[0]));
1083.}
1084. 
1085.void MergeSort(Test array[], const size_t array_count, const Comparison compare) {
1086.    Var(buffer, Allocate(Test, (array_count + 1)/2));
1087.    MergeSortR(array, Range_new(0, array_count), compare, buffer);
1088.    free(buffer);
1089.}
1090. 
1091. 
1092. 
1093. 
1094.size_t TestingRandom(size_t index, size_t total) {
1095.    return rand();
1096.}
1097. 
1098.size_t TestingRandomFew(size_t index, size_t total) {
1099.    return rand() * (100.0/RAND_MAX);
1100.}
1101. 
1102.size_t TestingMostlyDescending(size_t index, size_t total) {
1103.    return total - index + rand() * 1.0/RAND_MAX * 5 - 2.5;
1104.}
1105. 
1106.size_t TestingMostlyAscending(size_t index, size_t total) {
1107.    return index + rand() * 1.0/RAND_MAX * 5 - 2.5;
1108.}
1109. 
1110.size_t TestingAscending(size_t index, size_t total) {
1111.    return index;
1112.}
1113. 
1114.size_t TestingDescending(size_t index, size_t total) {
1115.    return total - index;
1116.}
1117. 
1118.size_t TestingEqual(size_t index, size_t total) {
1119.    return 1000;
1120.}
1121. 
1122.size_t TestingJittered(size_t index, size_t total) {
1123.    return (rand() * 1.0/RAND_MAX <= 0.9) ? index : (index - 2);
1124.}
1125. 
1126.size_t TestingMostlyEqual(size_t index, size_t total) {
1127.    return 1000 + rand() * 1.0/RAND_MAX * 4;
1128.}
1129. 
1130./* the last 1/5 of the data is random */
1131.size_t TestingAppend(size_t index, size_t total) {
1132.    if (index > total - total/5) return rand() * 1.0/RAND_MAX * total;
1133.    return index;
1134.}
1135. 
1136./* make sure the items within the given range are in a stable order */
1137./* if you want to test the correctness of any changes you make to the main WikiSort function,
1138. move this function to the top of the file and call it from within WikiSort after each step */
1139.#if VERIFY
1140.void WikiVerify(const Test array[], const Range range, const Comparison compare, const char *msg) {
1141.    size_t index;
1142.    for (index = range.start + 1; index < range.end; index++) {
1143.        /* if it's in ascending order then we're good */
1144.        /* if both values are equal, we need to make sure the index values are ascending */
1145.        if (!(compare(array[index - 1], array[index]) ||
1146.              (!compare(array[index], array[index - 1]) && array[index].index > array[index - 1].index))) {
1147.             
1148.            /*for (index2 = range.start; index2 < range.end; index2++) */
1149.            /*  printf("%lu (%lu) ", array[index2].value, array[index2].index); */
1150.             
1151.            printf("failed with message: %s\n", msg);
1152.            assert(false);
1153.        }
1154.    }
1155.}
1156.#endif
1157. 
1158.int main() {
1159.    size_t total, index;
1160.    double total_time, total_time1, total_time2;
1161.    const size_t max_size = 1500000;
1162.    Var(array1, Allocate(Test, max_size));
1163.    Var(array2, Allocate(Test, max_size));
1164.    Comparison compare = TestCompare;
1165.     
1166.    #if PROFILE
1167.        size_t compares1, compares2, total_compares1 = 0, total_compares2 = 0;
1168.    #endif
1169.    #if !SLOW_COMPARISONS && VERIFY
1170.        size_t test_case;
1171.        __typeof__(&TestingRandom) test_cases[] = {
1172.            TestingRandom,
1173.            TestingRandomFew,
1174.            TestingMostlyDescending,
1175.            TestingMostlyAscending,
1176.            TestingAscending,
1177.            TestingDescending,
1178.            TestingEqual,
1179.            TestingJittered,
1180.            TestingMostlyEqual,
1181.            TestingAppend
1182.        };
1183.    #endif
1184.     
1185.    /* initialize the random-number generator */
1186.    srand(time(NULL));
1187.    /*srand(10141985);*/ /* in case you want the same random numbers */
1188.     
1189.    total = max_size;
1190.     
1191.#if !SLOW_COMPARISONS && VERIFY
1192.    printf("running test cases... ");
1193.    fflush(stdout);
1194.     
1195.    for (test_case = 0; test_case < sizeof(test_cases)/sizeof(test_cases[0]); test_case++) {
1196.         
1197.        for (index = 0; index < total; index++) {
1198.            Test item;
1199.             
1200.            item.value = test_cases[test_case](index, total);
1201.            item.index = index;
1202.             
1203.            array1[index] = array2[index] = item;
1204.        }
1205.         
1206.        WikiSort(array1, total, compare);
1207.         
1208.        MergeSort(array2, total, compare);
1209.         
1210.        WikiVerify(array1, Range_new(0, total), compare, "test case failed");
1211.        for (index = 0; index < total; index++)
1212.            assert(!compare(array1[index], array2[index]) && !compare(array2[index], array1[index]));
1213.    }
1214.    printf("passed!\n");
1215.#endif
1216.     
1217.    total_time = Seconds();
1218.    total_time1 = total_time2 = 0;
1219.     
1220.    for (total = 0; total < max_size; total += 2048 * 16) {
1221.        double time1, time2;
1222.         
1223.        for (index = 0; index < total; index++) {
1224.            Test item;
1225.             
1226.            /* TestingRandom, TestingRandomFew, TestingMostlyDescending, TestingMostlyAscending, */
1227.            /* TestingAscending, TestingDescending, TestingEqual, TestingJittered, TestingMostlyEqual, TestingAppend */
1228.            item.value = TestingRandom(index, total);
1229.            #if VERIFY
1230.                item.index = index;
1231.            #endif
1232.             
1233.            array1[index] = array2[index] = item;
1234.        }
1235.         
1236.        time1 = Seconds();
1237.        #if PROFILE
1238.            comparisons = 0;
1239.        #endif
1240.        WikiSort(array1, total, compare);
1241.        time1 = Seconds() - time1;
1242.        total_time1 += time1;
1243.        #if PROFILE
1244.            compares1 = comparisons;
1245.            total_compares1 += compares1;
1246.        #endif
1247.         
1248.        time2 = Seconds();
1249.        #if PROFILE
1250.            comparisons = 0;
1251.        #endif
1252.        MergeSort(array2, total, compare);
1253.        time2 = Seconds() - time2;
1254.        total_time2 += time2;
1255.        #if PROFILE
1256.            compares2 = comparisons;
1257.            total_compares2 += compares2;
1258.        #endif
1259.         
1260.        printf("[%zu]\n", total);
1261.         
1262.        if (time1 >= time2)
1263.            printf("WikiSort: %f seconds, MergeSort: %f seconds (%f%% as fast)\n", time1, time2, time2/time1 * 100.0);
1264.        else
1265.            printf("WikiSort: %f seconds, MergeSort: %f seconds (%f%% faster)\n", time1, time2, time2/time1 * 100.0 - 100.0);
1266.         
1267.        #if PROFILE
1268.            if (compares1 <= compares2)
1269.                printf("WikiSort: %zu compares, MergeSort: %zu compares (%f%% as many)\n", compares1, compares2, compares1 * 100.0/compares2);
1270.            else
1271.                printf("WikiSort: %zu compares, MergeSort: %zu compares (%f%% more)\n", compares1, compares2, compares1 * 100.0/compares2 - 100.0);
1272.        #endif
1273.         
1274.        #if VERIFY
1275.            /* make sure the arrays are sorted correctly, and that the results were stable */
1276.            printf("verifying... ");
1277.            fflush(stdout);
1278.             
1279.            WikiVerify(array1, Range_new(0, total), compare, "testing the final array");
1280.            for (index = 0; index < total; index++)
1281.                assert(!compare(array1[index], array2[index]) && !compare(array2[index], array1[index]));
1282.             
1283.            printf("correct!\n");
1284.        #endif
1285.    }
1286.     
1287.    total_time = Seconds() - total_time;
1288.    printf("tests completed in %f seconds\n", total_time);
1289.    if (total_time1 >= total_time2)
1290.        printf("WikiSort: %f seconds, MergeSort: %f seconds (%f%% as fast)\n", total_time1, total_time2, total_time2/total_time1 * 100.0);
1291.    else
1292.        printf("WikiSort: %f seconds, MergeSort: %f seconds (%f%% faster)\n", total_time1, total_time2, total_time2/total_time1 * 100.0 - 100.0);
1293.     
1294.    #if PROFILE
1295.        if (total_compares1 <= total_compares2)
1296.            printf("WikiSort: %zu compares, MergeSort: %zu compares (%f%% as many)\n", total_compares1, total_compares2, total_compares1 * 100.0/total_compares2);
1297.        else
1298.            printf("WikiSort: %zu compares, MergeSort: %zu compares (%f%% more)\n", total_compares1, total_compares2, total_compares1 * 100.0/total_compares2 - 100.0);
1299.    #endif
1300.     
1301.    free(array1); free(array2);
1302.    return 0;
1303.}
1304. 
1305.            </limits.h></time.h></assert.h></math.h></string.h></stdarg.h></stdint.h></stdlib.h></stdio.h>

Zdroj

  • https://github.com/BonzaiThePenguin/WikiSort
  • https://en.m.wikipedia.org/wiki/Block_sort
  • https://en.wikipedia.org/wiki/Block_sort

SEO od společnosti Digital Pylon


Online casino s algoritmem

České casino online online slot-vegas.cz

Hrajte nejlepší hry jako je GoodGame Empire.





Zajímavé články: Jak najít práci snů? Zvolte kariéru v IT!, Češi mají rádi hrací automaty online, Jak funguje algoritmické obchodování Casino, Online výuka Algoritmus a online marketing mají svá pravidla, Automaty, Matematický vliv, Ratings, Jak fungují algoritmy hazardních her online: více znalostí, více peněz, SYPWAI - nástroj pro vědecký vývoj, Vynikají na globálním trhu: Nejlepší vývojáři softwaru pro online výherní automaty, Jak si vybrat nejlepší české online casino, Proč byste měli hrát online casino VPN revoluce, Kde najdeme algoritmy v každodenním životě?, Čeká vás pracovní pohovor mimo město? Podívejte se, jak dokonale zvládnout včasný příchod, 5 úžasných technologií ze světa hazardních her, Mirror and access to Mostbet, Svou kancelář můžete mít stále po ruce, Jaké výhody má digitalizovaná firma oproti off-line konkurenci?, Jaký systém vybrat pro snadné řízení výroby?, Nahradí umělá inteligence ajťáky?, Důvody, proč používat SnapTik ke stahování videí TikTok, Dokonalý den na pláži: Co si vzít s sebou, aby byl výlet zábavný a bezpečný?, Jak přežít dlouhý let?, Go pay GoodGame Empire, Blockchain, Rozhovor, Umělá inteligence, Ochranná známka pre softvér: Prečo ju registrovať?, Role kryptografických algoritmů v zabezpečení online kasin, Jaké jsou náklady na nákup 3D tiskárny?, Jak algoritmy vylepšují online zážitky v roce 2025,


Doporučujeme

Internet pro vaši firmu na míru

https://www.algoritmy.net