1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| def quickSort(nums, left, right): if left < right: pivot = partition(nums, left, right) # recursive quickSort(nums, left, pivot - 1) # left part quickSort(nums, pivot + 1, right) # right part
def partition(nums, left, right): for i in range(left,len(nums)-1): if nums[i] < nums[right]: # right is pivot nums[left], nums[i] = nums[i],nums[left] # swap smaller to left left += 1 # to next nums[left], nums[right] = nums[right], nums[left] # swap pivot print(nums, nums[right]) return left
nums = [ 10, 4, 40, 2, 3 ] print(nums) quickSort(nums, 0, len(nums) -1)
print('Sorted Array in Ascending Order:') print(nums)
> [10, 4, 40, 2, 3] [2, 3, 40, 10, 4] 4 [2, 3, 4, 10, 40] 40 [2, 3, 4, 10, 40] 40 Sorted Array in Ascending Order: [2, 3, 4, 10, 40]
|