|
| 1 | +# Python program for implementation of Quicksort Sort |
| 2 | + |
| 3 | +# This function takes last element as pivot, places |
| 4 | +# the pivot element at its correct position in sorted |
| 5 | +# array, and places all smaller (smaller than pivot) |
| 6 | +# to left of pivot and all greater elements to right |
| 7 | +# of pivot |
| 8 | +def partition(arr, low, high): |
| 9 | + i = (low - 1) # index of smaller element |
| 10 | + pivot = arr[high] # pivot |
| 11 | + |
| 12 | + for j in range(low, high): |
| 13 | + # If current element is smaller than the pivot |
| 14 | + if arr[j] < pivot: |
| 15 | + |
| 16 | + # increment index of smaller element |
| 17 | + i = i + 1 |
| 18 | + arr[i], arr[j] = arr[j], arr[i] |
| 19 | + |
| 20 | + arr[i + 1], arr[high] = arr[high], arr[i + 1] |
| 21 | + return i + 1 |
| 22 | + |
| 23 | +# The main function that implements QuickSort |
| 24 | +# arr[] --> Array to be sorted, |
| 25 | +# low --> Starting index, |
| 26 | +# high --> Ending index |
| 27 | + |
| 28 | +# Function to do Quick sort |
| 29 | +def quick_sort(arr, low, high): |
| 30 | + if low < high: |
| 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 | + quick_sort(arr, low, pi - 1) |
| 38 | + quick_sort(arr, pi + 1, high) |
| 39 | + |
| 40 | + |
| 41 | +# Driver code to test above |
| 42 | +if __name__ == '__main__': |
| 43 | + arr = [10, 7, 8, 9, 1, 5] |
| 44 | + n = len(arr) |
| 45 | + quick_sort(arr, 0, n - 1) |
| 46 | + print("Sorted array is:", arr) |
0 commit comments