From df08f321c23b77b9acd503a3dd4f9689916943bf Mon Sep 17 00:00:00 2001 From: Chirag Verma Date: Sun, 15 Oct 2023 22:06:52 +0530 Subject: [PATCH] Create quicksort --- Python/quicksort | 63 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 Python/quicksort diff --git a/Python/quicksort b/Python/quicksort new file mode 100644 index 00000000..4a38cb42 --- /dev/null +++ b/Python/quicksort @@ -0,0 +1,63 @@ +# Python program for implementation of Quicksort Sort + +# This implementation utilizes pivot as the last element in the nums list +# It has a pointer to keep track of the elements smaller than the pivot +# At the very end of partition() function, the pointer is swapped with the pivot +# to come up with a "sorted" nums relative to the pivot + + +# Function to find the partition position +def partition(array, low, high): + + # choose the rightmost element as pivot + pivot = array[high] + + # pointer for greater element + i = low - 1 + + # traverse through all elements + # compare each element with pivot + for j in range(low, high): + if array[j] <= pivot: + + # If element smaller than pivot is found + # swap it with the greater element pointed by i + i = i + 1 + + # Swapping element at i with element at j + (array[i], array[j]) = (array[j], array[i]) + + # Swap the pivot element with the greater element specified by i + (array[i + 1], array[high]) = (array[high], array[i + 1]) + + # Return the position from where partition is done + return i + 1 + +# function to perform quicksort + + +def quickSort(array, low, high): + if low < high: + + # Find pivot element such that + # element smaller than pivot are on the left + # element greater than pivot are on the right + pi = partition(array, low, high) + + # Recursive call on the left of pivot + quickSort(array, low, pi - 1) + + # Recursive call on the right of pivot + quickSort(array, pi + 1, high) + + +data = [1, 7, 4, 1, 10, 9, -2] +print("Unsorted Array") +print(data) + +size = len(data) + +quickSort(data, 0, size - 1) + +print('Sorted Array in Ascending Order:') +print(data)