Submission cd62d7ea...

ChallengeInteger sorting
Submitterricmoo.firefly.eth
Submitted at2018-51-01
Gas used1411176
pragma solidity 0.4.24;

contract Sort {

    function sort(uint[] input) public pure returns(uint[]) {
        uint length = input.length;
        if (length <= 1) { return input; }

        uint i;

        // Count ordered elements
        uint asc = 0;
        for (i = length - 1; i > 0; i--) {
            if (input[i] >= input[i - 1]) { asc++; }
        }

        // If Almost entirely reversed, reverse it
        if (asc < (length / 4)) {
            uint end = length / 2;
            for (i = 0; i < end; i++) {
                (input[i], input[length - i - 1]) = (input[length - i - 1], input[i]);
            }
            asc = length - asc - 1;
        }

        // Already sorted
        if ((asc + 1) == length) { return input; }

        // QuickSort
        if (asc + 8 < length) {
            sort(input, 0, uint(length - 1));
        }

        // Linear Insertion Sort
        // See: https://en.wikipedia.org/wiki/Insertion_sort
        for (i = 1; i < length; i++) {
            uint256 tmp = input[i];
            int256 j = int(i) - 1;
            while (j >= 0 && input[uint(j)] > tmp) {
                input[uint(j) + 1] = input[uint(j)];
                j--;
            }
            input[uint(j) + 1] = tmp;
        }

        return input;
    }

    // Quick Sort (Hoare partition scheme)
    // See: https://en.wikipedia.org/wiki/Quicksort
    function sort(uint[] A, uint lo, uint hi) internal pure {
       // @TODO: Perform large number of sample sorts to find the best
       // value (or curve) for this, based on sample size
       if (hi - lo > 8) {
            uint p = partition(A, lo, hi);
            sort(A, lo, p);
            sort(A, p + 1, hi);
        }
    }

    function partition(uint[] A, uint lo, uint hi) internal pure returns (uint) {
        uint pivot = A[uint(lo)];

        // Note: May temporarility overflow below 0, but will be corrected in the first loop
        uint i = lo - 1;
        uint j = hi + 1;
        while (true) {
            uint a;
            uint b;
            while(true) {
                i++;
                a = A[uint(i)];
                if (a >= pivot) { break; }
            }
            while(true) {
                j--;
                b = A[uint(j)];
                if (b <= pivot) { break; }
            }

            if (i >= j) { return j; }

            //(A[uint(i)], A[uint(j)]) = (A[uint(j)], A[uint(i)]);
            (A[uint(i)], A[uint(j)]) = (b, a);
        }
    }

}