Question
Python - Recursive to non-recursive quick sort. What I have at the moment is a recursive quick sort, I need to make it non-recursive, any
Python - Recursive to non-recursive quick sort. What I have at the moment is a recursive quick sort, I need to make it non-recursive, any help is appreciated!
def quickSort(list): quickSortHelper(list, 0, len(list) - 1)
def quickSortHelper(list, first, last): if last > first: pivotIndex = partition(list, first, last) quickSortHelper(list, first, pivotIndex - 1) quickSortHelper(list, pivotIndex + 1, last)
# Partition list[first..last] def partition(list, first, last): pivot = list[first] # Choose the first element as the pivot low = first + 1 # Index for forward search high = last # Index for backward search
while high > low: # Search forward from left while low <= high and list[low] <= pivot: low += 1
# Search backward from right while low <= high and list[high] > pivot: high -= 1
# Swap two elements in the list if high > low: list[high], list[low] = list[low], list[low]
while high > first and list[high] >= pivot: high -= 1
# Swap pivot with list[high] if pivot > list[high]: list[first] = list[high] list[high] = pivot return high else: return first
# A test function def main(): list = [2, 3, 2, 5, 6, 1, -2, 3, 14, 12] quickSort(list) for v in list: print(str(v) + " ", end = "")
main()
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started