|
| 1 | +# Quick sort in Python |
| 2 | + |
| 3 | +# The basic idea behind Quick Sort is to first find an element Pivot from the array |
| 4 | +# Based on pivot element, the array is sorted such that all the elements to the left of pivot are smaller |
| 5 | +# than pivot and elements to right of pivot are greater than pivot |
| 6 | +# The same process is repeated in the left and right sub array of the pivot. |
| 7 | + |
| 8 | + |
| 9 | +# function to find the partition position |
| 10 | +def partition(array, low, high): |
| 11 | + |
| 12 | + # choose the rightmost element as pivot |
| 13 | + pivot = array[high] |
| 14 | + |
| 15 | + # pointer for greater element |
| 16 | + i = low - 1 |
| 17 | + |
| 18 | + # traverse through all elements |
| 19 | + # compare each element with pivot |
| 20 | + for j in range(low, high): |
| 21 | + if array[j] <= pivot: |
| 22 | + # if element smaller than pivot is found |
| 23 | + # swap it with the greater element pointed by i |
| 24 | + i = i + 1 |
| 25 | + |
| 26 | + # swapping element at i with element at j |
| 27 | + (array[i], array[j]) = (array[j], array[i]) |
| 28 | + |
| 29 | + # swap the pivot element with the greater element specified by i |
| 30 | + (array[i + 1], array[high]) = (array[high], array[i + 1]) |
| 31 | + |
| 32 | + # return the position from where partition is done |
| 33 | + return i + 1 |
| 34 | + |
| 35 | +def quickSort(array, low, high): |
| 36 | + if low < high: |
| 37 | + |
| 38 | + # find pivot element such that |
| 39 | + # element smaller than pivot are on the left |
| 40 | + # element greater than pivot are on the right |
| 41 | + pi = partition(array, low, high) |
| 42 | + |
| 43 | + # recursive call on the left of pivot |
| 44 | + quickSort(array, low, pi - 1) |
| 45 | + |
| 46 | + # recursive call on the right of pivot |
| 47 | + quickSort(array, pi + 1, high) |
| 48 | + |
| 49 | + |
| 50 | +data = [10, 11, 3, 5, 16, 34, 15] |
| 51 | +print("Unsorted Array") |
| 52 | +print(data) |
| 53 | + |
| 54 | +size = len(data) |
| 55 | + |
| 56 | +quickSort(data, 0, size - 1) |
| 57 | + |
| 58 | +print('Sorted Array in Ascending Order:') |
| 59 | +print(data) |
0 commit comments