| 1 | def partition(nums, low, high): |
| 2 | # We select the middle element to be the pivot. Some implementations select |
| 3 | # the first element or the last element. Sometimes the median value becomes |
| 4 | # the pivot, or a random one. There are many more strategies that can be |
| 5 | # chosen or created. |
| 6 | pivot = nums[(low + high) // 2] |
| 7 | i = low - 1 |
| 8 | j = high + 1 |
| 9 | while True: |
| 10 | i += 1 |
| 11 | while nums[i] < pivot: |
| 12 | i += 1 |
| 13 | |
| 14 | j -= 1 |
| 15 | while nums[j] > pivot: |
| 16 | j -= 1 |
| 17 | |
| 18 | if i >= j: |
| 19 | return j |
| 20 | |
| 21 | # If an element at i (on the left of the pivot) is larger than the |
| 22 | # element at j (on right right of the pivot), then swap them |
| 23 | nums[i], nums[j] = nums[j], nums[i] |
| 24 | |
| 25 | |
| 26 | def quick_sort(nums): |