|
| 1 | +# Algorithm: |
| 2 | +# Select pivot, low, and high elements. |
| 3 | +# Keep moving low & high pointers until we found the indexes which satisfies the conditions: |
| 4 | +# A[low] > A[pivot] and A[high] <= A[pivot] |
| 5 | +# If low < high then swap A[low] with A[high] and |
| 6 | +# If low >= high then swap A[pivot] with A[high] |
| 7 | + |
| 8 | +def swap(a, b, arr): |
| 9 | + if a != b: |
| 10 | + arr[a], arr[b] = arr[b], arr[a] |
| 11 | + |
| 12 | + |
| 13 | +# Hoare partition |
| 14 | +def partition(elements, start, end): |
| 15 | + pivot_index = start # taking the first index(0) as a pivot in Hoare's partition |
| 16 | + pivot = elements[pivot_index] # pivot index value |
| 17 | + while start < end: # these while loops will stop at the index which satisfies the conditions |
| 18 | + while start < len(elements) and elements[start] <= pivot: # start < size and start value <= pivot value |
| 19 | + start += 1 # incrementing start index pointer, i.e. start points to index 2 now, if it pointed to 1 before |
| 20 | + |
| 21 | + while elements[end] > pivot: # it will stop when pivot value > then end value, so we have found the index |
| 22 | + end -= 1 # decrementing end index pointer, i.e. end points to index 5 now, if it pointed to 6 before |
| 23 | + |
| 24 | + if start < end: |
| 25 | + swap(start, end, elements) |
| 26 | + |
| 27 | + swap(pivot_index, end, elements) # when end >= start, swapping end with pivot, the pivot value at end index will be |
| 28 | + return end # sorted element, which is at its perfect index |
| 29 | + |
| 30 | + |
| 31 | +def partitions(elements, start, end): |
| 32 | + pivot = elements[end] |
| 33 | + pi = start |
| 34 | + for i in range(start, end): |
| 35 | + if elements[i] <= pivot: |
| 36 | + swap(i, pi, elements) |
| 37 | + pi += 1 |
| 38 | + swap(pi, end, elements) |
| 39 | + return pi |
| 40 | + |
| 41 | + |
| 42 | +def quick_sort(elements, start, end): |
| 43 | + if start < end: |
| 44 | + pi = partition(elements, start, end) # after finding the middle element we store that at pi index in the Array |
| 45 | + quick_sort(elements, start, pi - 1) # in the 0 to pi-1 array & pi +1 to end array, we will again find |
| 46 | + quick_sort(elements, pi + 1, end) # partition index(pi) and divide these arrays further till one element |
| 47 | + # remains which is implicitly sorted |
| 48 | + |
| 49 | + |
| 50 | +if __name__ == '__main__': |
| 51 | + elements = [11, 9, 29, 7, 2, 15, 28] |
| 52 | + quick_sort(elements, 0, len(elements) - 1) |
| 53 | + print(elements) |
0 commit comments