fork download
  1. # Quick sort in Python
  2.  
  3. # function to find the partition position
  4. def partition(array, low, high):
  5.  
  6. # choose the rightmost element as pivot
  7. pivot = array[high]
  8.  
  9. # pointer for greater element
  10. i = low - 1
  11.  
  12. # traverse through all elements
  13. # compare each element with pivot
  14. for j in range(low, high):
  15. if array[j] <= pivot:
  16. # if element smaller than pivot is found
  17. # swap it with the greater element pointed by i
  18. i = i + 1
  19.  
  20. # swapping element at i with element at j
  21. (array[i], array[j]) = (array[j], array[i])
  22.  
  23. # swap the pivot element with the greater element specified by i
  24. (array[i + 1], array[high]) = (array[high], array[i + 1])
  25.  
  26. # return the position from where partition is done
  27. return i + 1
  28.  
  29. # function to perform quicksort
  30. def quickSort(array, low, high):
  31. if low < high:
  32.  
  33. # find pivot element such that
  34. # element smaller than pivot are on the left
  35. # element greater than pivot are on the right
  36. pi = partition(array, low, high)
  37.  
  38. # recursive call on the left of pivot
  39. quickSort(array, low, pi - 1)
  40.  
  41. # recursive call on the right of pivot
  42. quickSort(array, pi + 1, high)
  43.  
  44.  
  45. data = [8, 7, 2, 1, 0, 9, 6]
  46. print("Unsorted Array")
  47. print(data)
  48.  
  49. size = len(data)
  50.  
  51. quickSort(data, 0, size - 1)
  52.  
  53. print('Sorted Array in Ascending Order:')
  54. print(data)
Success #stdin #stdout 0.04s 9692KB
stdin
Standard input is empty
stdout
Unsorted Array
[8, 7, 2, 1, 0, 9, 6]
Sorted Array in Ascending Order:
[0, 1, 2, 6, 7, 8, 9]