0

Im having a problem to understand this algorithm, how would you describe it, mostly the while loops. I understand that this i an iterative function, and the use of Hoare partition scheme. But what does the while loops do, and why does it use breaks.

def inplace_quick_sort_nonrecursive(S):
    if len(S) < 2:
      return S
    stack = []                          #initialize the stack
    stack.append([0, len(S) - 1])       
    while len(stack) > 0:               #loop till the stack is empty
      low, high = stack.pop()           #pop low and high indexes 
      pivot = S[(low + high) // 2]      #create pivot, of any S[] except S[high]
      i = low - 1                       #Hoare partition
      j = high + 1
      while True:
        while True:                     #while (S[++i] < pivot)
          i += 1
          if(S[i] >= pivot):
            break
        while True:                       #while(S[--j] < p)
          j -= 1
          if(S[j] <= pivot):
            break
        if (i >= j):                    #if indexes met or crossed, break
          break
        S[i], S[j] = S[j], S[i]         #else swap the elements
      if (j > low):                     #push the indexes into the stack
        stack.append([low, j])
      j += 1
      if (high > j):
        stack.append([j, high])
j0can
  • 21
  • 6
  • [visualgo](https://visualgo.net/en/sorting) try this :) – Raghul Thangavel Mar 18 '21 at 11:24
  • It looks like the [Hoare partition scheme](https://en.wikipedia.org/wiki/Quicksort#Hoare_partition_scheme). Try to read the Wikipedia article. – Andy Sukowski-Bang Mar 18 '21 at 11:26
  • That looks like my code. The while loops are used because Python doesn't have pre-increment or pre-decrement operators and doesn't have do while. You can see the same algorithm in C++ in [this answer](https://stackoverflow.com/questions/66531479#66534116). The first implementations of quicksort were also iterative, because the systems they ran on didn't have a native stack. Hoare use the term "nest" instead of stack in his early papers. – rcgldr Mar 18 '21 at 19:05

0 Answers0