|
1 | | -def partition(arr, low, high): |
| 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] |
2 | 7 | i = low - 1 |
3 | | - pivot = arr[high] |
4 | | - |
5 | | - for j in range(low, high): |
6 | | - if arr[j] <= pivot: |
7 | | - i = i + 1 |
8 | | - arr[i], arr[j] = arr[j], arr[i] |
9 | | - |
10 | | - arr[i + 1], arr[high] = arr[high], arr[i + 1] |
11 | | - return i + 1 |
12 | | - |
13 | | - |
14 | | -def quickSort(arr, low, high): |
15 | | - if low < high: |
16 | | - pi = partition(arr, low, high) |
17 | | - quickSort(arr, low, pi - 1) |
18 | | - quickSort(arr, pi + 1, high) |
19 | | - |
20 | | - |
21 | | -arr = [10, 7, 8, 9, 1, 5] |
22 | | -print("Initial array is:", arr) |
23 | | -n = len(arr) |
24 | | -quickSort(arr, 0, n - 1) |
25 | | -# patch-1 |
26 | | -# print("Sorted array is:", arr) |
27 | | -# ======= |
28 | | -print("Sorted array is:") |
29 | | -# patch-4 |
30 | | -# for i in range(0,n): |
31 | | -# ======= |
32 | | -for i in range(0, len(arr)): |
33 | | - # master |
34 | | - print(arr[i], end=" ") |
35 | | - |
36 | | -# your code is best but now it is easy to understand |
37 | | -# master |
| 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): |
| 27 | + # Create a helper function that will be called recursively |
| 28 | + def _quick_sort(items, low, high): |
| 29 | + if low < high: |
| 30 | + # This is the index after the pivot, where our lists are split |
| 31 | + split_index = partition(items, low, high) |
| 32 | + _quick_sort(items, low, split_index) |
| 33 | + _quick_sort(items, split_index + 1, high) |
| 34 | + |
| 35 | + _quick_sort(nums, 0, len(nums) - 1) |
| 36 | + |
| 37 | + |
| 38 | +# Verify it works |
| 39 | +random_list_of_nums = [22, 5, 1, 18, 99] |
| 40 | +quick_sort(random_list_of_nums) |
| 41 | +print(random_list_of_nums) |
0 commit comments