Submission df0a8f9e...

ChallengeInteger sorting
Submitter0xff3c2241cd767b7...
Submitted at2018-34-24
Gas used1036285
/**
 * 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 {

    // This implementation: 1100358
    /**
     * @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 constant returns(uint[]) {
       if (input.length<=1){
         return input;
       }
       quickSort(input, 0, input.length-1);
       return input;
    }

    function quickSort(uint[] memory input, uint lo, uint hi) internal {
      uint lo2 = lo;
      uint hi2 = hi;
      uint pivot = input[(hi2+lo2)/2]; // Yeah, this could overflow... but surely the test arrays aren't that long
      while (true){
        while (input[lo2] < pivot){
          lo2 += 1;
        }
        while (input[hi2] > pivot){
          hi2 -= 1;
        }
        if (lo2 >= hi2){
          break;
        }
        (input[lo2], input[hi2]) = (input[hi2], input[lo2]);
        // Only time next iteration of loop wouldn't do this is if input[lo] = pivot... but that can't be true, because
        // we chose the elements to switch based on them being strictly greater or smaller. So doing this here skips the first
        // evaluation of the inner while loops, which we know would always happen.
        lo2 += 1;
        hi2 -= 1;
      }
      if (lo < hi2){
        quickSort(input, lo, hi2);
      }
      if (hi2+1 < hi){
        quickSort(input, hi2+1, hi);
      }
    }

}