Quick sort algorithm in python with code code example
Example 1: Quick Sort python
def partition(array, begin, end):
pivot_idx = begin
for i in xrange(begin+1, end+1):
if array[i] <= array[begin]:
pivot_idx += 1
array[i], array[pivot_idx] = array[pivot_idx], array[i]
array[pivot_idx], array[begin] = array[begin], array[pivot_idx]
return pivot_idx
def quick_sort_recursion(array, begin, end):
if begin >= end:
return
pivot_idx = partition(array, begin, end)
quick_sort_recursion(array, begin, pivot_idx-1)
quick_sort_recursion(array, pivot_idx+1, end)
def quick_sort(array, begin=0, end=None):
if end is None:
end = len(array) - 1
return quick_sort_recursion(array, begin, end)
Example 2: quicksort code in python
def pivot_place(list1,first,last):
pivot = list1[first]
left = first + 1
right = last
while True :
while left <= right and list1[left] <= pivot :
left += 1
while left<=right and list1[right] >= pivot:
right -= 1
if right < left :
break
else:
list1[left],list1[right] = list1[right],list1[left]
list1[first],list1[right] = list1[right],list1[first]
return right
def quicksort(list1,first,last):
if first < last :
p = pivot_place(list1,first,last)
quicksort(list1,first,p-1)
quicksort(list1,p+1,last)
n = int(input("How many elements you want : "))
list1 = [int(input("Enter elements : ")) for x in range(n)]
quicksort(list1,0,n - 1)
print(list1)