fork download
  1. import random
  2. import sys
  3. sys.setrecursionlimit(1000000) # allow deeper recursion if needed
  4.  
  5. class Solution(object):
  6. def sortArray(self, nums):
  7. self.quickSort(nums, 0, len(nums) - 1)
  8. return nums
  9.  
  10. def quickSort(self, nums, low, high):
  11. if low >= high:
  12. return
  13.  
  14. # choose random pivot and move it to the end
  15. pivotIndex = random.randint(low, high)
  16. self.swap(nums, pivotIndex, high)
  17. pivot = nums[high]
  18.  
  19. # 3-way partition
  20. lt = low # nums[low..lt-1] < pivot
  21. i = low # nums[lt..i-1] == pivot
  22. gt = high # nums[gt+1..high] > pivot
  23. while i <= gt:
  24. if nums[i] < pivot:
  25. self.swap(nums, lt, i)
  26. lt += 1
  27. i += 1
  28. elif nums[i] > pivot:
  29. self.swap(nums, i, gt)
  30. gt -= 1
  31. else:
  32. i += 1
  33.  
  34. # recurse on < and > parts
  35. self.quickSort(nums, low, lt - 1)
  36. self.quickSort(nums, gt + 1, high)
  37.  
  38. def swap(self, nums, i, j):
  39. nums[i], nums[j] = nums[j], nums[i]
  40.  
Success #stdin #stdout 0.1s 14308KB
stdin
Standard input is empty
stdout
Standard output is empty