Комментарии:
Sir your mail id ..i have some doubts
Ответитьsir How the complexity will ne O n
When we have 3for loops
I think it will greater than that
So good explanation ...thanks!
ОтветитьA simple approach I came up with. After the first pass, all the zeroes are sent to the left. After the second pass, all the ones are sent to the right of zeroes. Here is the code:
A = [0, 1, 2, 1, 1, 1, 0, 2, 2, 0, 1, 2]
left = 0; right = 0
while right < len(A):
if A[right] == 0:
A[left], A[right] = A[right], A[left]
left += 1
right += 1
left = 0; right = 0
while right < len(A):
if A[right] == 1:
A[left], A[right] = A[right], A[left]
left += 1
elif A[right] == 0:
left += 1
right += 1
print(A)
Edit: This approach is used in Quicksort for moving all the elements lesser than pivot to its left and greater than pivot to its right.
Space complexity?
ОтветитьWas a classic DNF problem, should have shown that. Binge watching your algos Playlist, good job.
ОтветитьSir can we use bubble sort as well
ОтветитьIn real scenarios you will most likely be sorting the items with three tags or 0,1,2 as objects that have real data in them. This approach wouldn't work on that.
ОтветитьCan we use Arrays.sort(a);
ОтветитьThanks, now I got a clear picture.
ОтветитьHow to get 0,2,1 from above array
Ответить