|
| 1 | +# function to find the partition position |
| 2 | + |
| 3 | +def partition(array, low, high): |
| 4 | + pivot = array[high] #pivot element |
| 5 | + |
| 6 | + #index of smaller element |
| 7 | + i = low - 1 |
| 8 | + |
| 9 | + # traverse through all elements |
| 10 | + # compare each element with pivot |
| 11 | + for j in range(low, high): |
| 12 | + if array[j] <= pivot: |
| 13 | + # if current element smaller than pivot is found |
| 14 | + #increment index of smaller element |
| 15 | + i = i + 1 |
| 16 | + |
| 17 | + # swapping element at i with element at j |
| 18 | + (array[i], array[j]) = (array[j], array[i]) |
| 19 | + |
| 20 | + # swap the pivot element with the greater element specified by i |
| 21 | + (array[i + 1], array[high]) = (array[high], array[i + 1]) |
| 22 | + |
| 23 | + # return the position from where partition is done |
| 24 | + return i + 1 |
| 25 | + |
| 26 | +# quicksort function |
| 27 | +def quickSort(array, low, high): |
| 28 | + if low < high: |
| 29 | + #pi is partitioning index |
| 30 | + pi = partition(array, low, high) |
| 31 | + |
| 32 | + # Separately sort elements before partition and after partition |
| 33 | + quickSort(array, low, pi - 1) |
| 34 | + quickSort(array, pi + 1, high) |
| 35 | + |
| 36 | + |
| 37 | +size= int(input("Enter number of elements ")) |
| 38 | +data=list(map(int,input("\nEnter the numbers: ").strip().split()))[:size] |
| 39 | +print("Unsorted Array") |
| 40 | +print(data) |
| 41 | +quickSort(data, 0, size - 1) |
| 42 | +print('Sorted Array in Ascending Order:') |
| 43 | +print(data) |
0 commit comments