Submission 81f4e68b...

ChallengeInteger sorting
Submittercottenio.eth
Submitted at2018-26-30
Gas used1090116
/**
 * This file is part of the 1st Solidity Gas Golfing Contest.
 *
 * This work is licensed under Creative Commons Attribution ShareAlike 3.0.
 * https://creativecommons.org/licenses/by-sa/3.0/
 */

pragma solidity 0.4.24;

contract Sort {
    uint constant UINT256_MAX = 2**256-1;

    /**
     * @dev Sorts a list of integers in ascending order.
     *
     * The input list may be of any length.
     * BENCHMARK: Double Pivot QuickSort
     *
     * @param input The list of integers to sort.
     * @return The sorted list.
     */
    function sort(uint[] input) public pure returns(uint[]) {
        uint n = input.length;

        if (n < 2) {
            return input;
        }

        quickSort(input, 0, n-1);

        return input;
    }

    function quickSort(uint[] memory arr, uint left, uint right) pure internal {
        uint i = left;
        uint j = right;

        uint pivot = arr[(left + (right - left) / 2)];

        while (i <= j && j != UINT256_MAX) {
            while (arr[i] < pivot) i++;
            while (pivot < arr[j]) j--;
            if (i <= j) {
                (arr[i], arr[j]) = (arr[j], arr[i]);
                i++;
                j--;
            }
        }

        if (left < j && j != UINT256_MAX)
            quickSort(arr, left, j);
        if (i < right)
            quickSort(arr, i, right);
    }
}