Submission dab36e60...

ChallengeInteger sorting
Submitter0x6b9205614d2523d...
Submitted at2018-39-08
Gas used663370
pragma solidity 0.4.24;


contract Sort {

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

    function sort(uint[] arr, uint left, uint right) internal pure {
        uint i = left;
        uint j = right;
        uint pivot = 0;
        assembly {
            pivot := mload(add(add(arr, 0x20), mul(0x20, add(left, div(sub(right, left), 2)))))
        }
        assembly {
            for {} or(gt(j, i), eq(j, i)) {} {
                for {} lt(mload(add(add(arr, 0x20), mul(i, 0x20))), pivot) {} {
                    i := add(i, 1)
                }

                for {} lt(pivot, mload(add(add(arr, 0x20), mul(j, 0x20)))) {} {
                    j  := sub(j, 1)
                }
                switch or(gt(j, i), eq(j, i))
                case 1 {
                    let temp := mload(add(add(arr, 0x20), mul(i, 0x20)))
                    mstore(add(add(arr, 0x20), mul(i, 0x20)), mload(add(add(arr, 0x20), mul(j, 0x20))))
                    mstore(add(add(arr, 0x20), mul(j, 0x20)), temp)
                    i := add(i, 1)
                    j  := sub(j, 1)
                }
            }
        }
        if (left < j)
            sort(arr, left, j);
        if (i < right)
            sort(arr, i, right);
    }
}