Friday, April 30, 2021

Dutch Flag problem

Dutch flag is a notable problem wherein you have a array representing three colors . Red(R), Green(G) and Blue(B) which needs to be sorted with Reds coming first followed by Green and then Blue. This is achieved by lumoto partitioning scheme.
arr = ['G','B','R','G','B','G','R']
ridx=0
bidx=len(arr)-1
i=0
while(i<bidx):
if(arr[i] == 'R'):
arr[i],arr[ridx] = arr[ridx],arr[i]
ridx += 1
i = i+1
elif (arr[i] == 'B'):
arr[i],arr[bidx] = arr[bidx], arr[i]
bidx -= 1
else:
i=i+1
print(arr)
view raw dutchflag.py hosted with ❤ by GitHub

No comments:

Post a Comment