How do i make the bottom function non-recursive, ive tried but by creating new functions which is not the point in this problem. The first function is given and the inplace_quicksort_non_recursive is created by me.
import random
def inplace_quick_sort(S, a, b):
"""Sort the list from S[a] to S[b] inclusive using the quick-sort algorithm."""
if a >= b: return # range is trivially sorted
pivot = S[b] # last element of range is pivot
left = a # will scan rightward
right = b-1 # will scan leftward
while left <= right:
# scan until reaching value equal or larger than pivot (or right marker)
while left <= right and S[left] < pivot:
left += 1
# scan until reaching value equal or smaller than pivot (or left marker)
while left <= right and pivot < S[right]:
right -= 1
if left <= right: # scans did not strictly cross
S[left], S[right] = S[right], S[left] # swap values
left, right = left + 1, right - 1 # shrink range
# put pivot into its final place (currently marked by left index)
S[left], S[b] = S[b], S[left]
# make recursive calls
inplace_quick_sort(S, a, left - 1)
inplace_quick_sort(S, left + 1, b)
return left
def inplace_quick_sort_nonrecursive(S):
stack = [] # create a stack for storing sublist start and end index
a = 0 # get the starting and ending index of a given list
b = len(S) - 1
pivot = S[b]
stack.append((a, b)) # push the start and end index of the array into the stack
while len(stack) > 0: # loop till stack is empty
a, b = stack.pop() # remove top pair from the list and get sublist starting and ending indices
pivot = inplace_quick_sort(S, a, b) # rearrange elements across pivot
if pivot - 1 > a: # push sublist indices containing elements that are less than the current pivot to stack
stack.append((a, pivot - 1))
if pivot + 1 < b: # push sublist indices containing elements that are more than the current pivot to stack
stack.append((pivot + 1, b))
origList = random.sample(range(100), 100)
origList2 = random.sample(range(100), 100)
origList.extend(origList2)
inplace_quick_sort_nonrecursive(origList)
errorIndices = []
for i in range(100):
ind1 = 2*i
ind2 = ind1+1
if origList[ind1] != i:
errorIndices.append(ind1)
if origList[ind2] != i:
errorIndices.append(ind2)
if len(errorIndices) == 0:
print("PASSED")
else:
print("Error in indices: " + str(errorIndices))
What do i need to create so the bottom function becomes non-recursive