Illustration:
array[] = [15, 85, 35, 95, 45, 55, 75, 77]low = 0, high = 7, pivot = arr[high] = 77index of smaller element, index = -1Traverse: j = low to high-1j = 0 : array[j] <= pivot, do i++ and swap(array[index], array[j])index = 0array[] = [15, 85, 35, 95, 45, 55, 75, 77] # as index and j are same#so no changej = 1 : Since array[j] > pivot # No Change in anywherej = 2 : Since array[j] <= pivot, do index++ and swap(array[index], array[j])index = 1array[] = [15, 35, 85, 95, 45, 55, 75, 77] # swapping 85 and 35j = 3 : array[j] > pivot, So no change in anywherej = 4 : Since array[j] <= pivot, do i++ and swap(array[index], array[j])index = 2array[] = [15, 35, 45, 95, 85, 55, 75, 77] #Swapping 85 and 45j = 5 : array[j] <= pivot, do index++ and swap(array[index], array[j])index = 3array[] = [15, 35, 45, 55, 85, 95, 75, 77] # Swapping 95 and 55j = 6 : arr[j] <= pivot, do index++ and swap(array[index], array[j])index = 4array[] = [15, 35, 45, 55, 75, 95, 85, 77]Now Swap(array[i+1], array[high]) because j == high-1array[] = [15, 35, 45, 55, 75, 77, 85, 95] # swapping 95 and 77
Code:
def partition(array, low, high):
pivot = array[high]
index = low - 1
for j in range(low, high):
if array[j] < pivot:
index += 1
array[index], array[j] = array[j], array[index]
array[index + 1], array[high] = array[high], array[index + 1]
return index + 1
def quickSort(array, low, high):
if low < high:
mid = partition(array,low,high)
quickSort(array, low, mid - 1)
quickSort(array, mid+1, high)
if __name__ == "__main__":
array = [10,8,7,9,2,4]
quickSort(array,0,len(array)-1)
print("Sorted array is: ")
for i in array:
print(i,end=' ')
print("\n")
Comments
Post a Comment
If you've any doubts, please let me text