Submission 51d95ba8...

ChallengeInteger sorting
Submitter0x9e0ad99de20a444...
Submitted at2018-40-14
Gas used715881
pragma solidity 0.4.24;
/*QuickSortarray*/
contract Sort {
    /**
     * @dev Sorts a list of integers in ascending order.
     *
     * The input list may be of any length.
     *
     * @param input The list of integers to sort.
     * @return The sorted list.
     */
    function sort(uint[] input) public pure returns(uint[]) {
        uint inputLen = input.length;
        bool ordered = true;
        bool inversedOrdered = true;
        
        if(inputLen == 0)
            return input;

        for(uint n = 0;n < (inputLen-2)/4;n++){
            if(input[n] > input[n+1]){
                ordered = false;
                break;
            }
        }

        if(ordered)
            return input;

        for(n = 0;n < (inputLen-2)/4;n++){
            if(input[n] < input[n+1]){
                inversedOrdered = false;
                break;
            }
        }

        if(inversedOrdered){

            for(n = 0;n < inputLen/2;n++){
                (input[n],input[inputLen-n-1]) = (input[inputLen-n-1],input[n]);
            }
            return input;
        }   
        
        quickSort(input, 0, inputLen - 1);
        return input;
    }

    function quickSort(uint[] input, uint low, uint high) internal pure {
        uint i = low;
        uint j = high;
        uint pivot = input[low + (high - low) / 2];

        while (i <= j){
            while (input[i] < pivot){
                i++;
            } 
            while (pivot < input[j]){
                j--;
            } 
            if (i <= j){
                (input[i], input[j]) = (input[j], input[i]);
                i++;
                j--;
            }
        }
        if (low < j)
            quickSort(input, low, j);
        if (i < high)
            quickSort(input, i, high);
    }
}