quickSort array python code example
Example 1: 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)
Example 2: quicksort in python
def partition(arr, low, high):
i = (low-1)
pivot = arr[high]
for j in range(low, high):
if arr[j] <= pivot:
i = i+1
arr[i], arr[j] = arr[j], arr[i]
arr[i+1], arr[high] = arr[high], arr[i+1]
return (i+1)
def quickSort(arr, low, high):
if len(arr) == 1:
return arr
if low < high:
pi = partition(arr, low, high)
quickSort(arr, low, pi-1)
quickSort(arr, pi+1, high)
arr = [10, 7, 8, 9, 1, 5]
n = len(arr)
quickSort(arr, 0, n-1)
print("Sorted array is:")
for i in range(n):
print("%d" % arr[i]),