|
| 1 | +def partition(arr, low, high): |
| 2 | + i = (low-1) # index of smaller element |
| 3 | + pivot = arr[high] # pivot |
| 4 | + |
| 5 | + for j in range(low, high): |
| 6 | + |
| 7 | + # If current element is smaller than or |
| 8 | + # equal to pivot |
| 9 | + if arr[j] <= pivot: |
| 10 | + |
| 11 | + # increment index of smaller element |
| 12 | + i = i+1 |
| 13 | + arr[i], arr[j] = arr[j], arr[i] |
| 14 | + |
| 15 | + arr[i+1], arr[high] = arr[high], arr[i+1] |
| 16 | + return (i+1) |
| 17 | + |
| 18 | +# The main function that implements QuickSort |
| 19 | +# arr[] --> Array to be sorted, |
| 20 | +# low --> Starting index, |
| 21 | +# high --> Ending index |
| 22 | + |
| 23 | +# Function to do Quick sort |
| 24 | + |
| 25 | + |
| 26 | +def quickSort(arr, low, high): |
| 27 | + if len(arr) == 1: |
| 28 | + return arr |
| 29 | + if low < high: |
| 30 | + |
| 31 | + # pi is partitioning index, arr[p] is now |
| 32 | + # at right place |
| 33 | + pi = partition(arr, low, high) |
| 34 | + |
| 35 | + # Separately sort elements before |
| 36 | + # partition and after partition |
| 37 | + quickSort(arr, low, pi-1) |
| 38 | + quickSort(arr, pi+1, high) |
| 39 | + |
| 40 | + |
| 41 | +# Driver code to test above |
| 42 | +arr = [10, 7, 8, 9, 1, 5] |
| 43 | +n = len(arr) |
| 44 | +quickSort(arr, 0, n-1) |
| 45 | +print("Sorted array is:") |
| 46 | +for i in range(n): |
| 47 | + print("%d" % arr[i]), |
| 48 | + |
0 commit comments