Sort an Array of 0s, 1s and 2s

Sort an Array of 0s, 1s and 2s

Programming Tutorials

6 лет назад

12,738 Просмотров

Ссылки и html тэги не поддерживаются


Комментарии:

@mohammedajazquadri7869
@mohammedajazquadri7869 - 22.12.2019 21:14

Sir your mail id ..i have some doubts

Ответить
@ujjwaljain1939
@ujjwaljain1939 - 28.04.2020 12:37

sir How the complexity will ne O n
When we have 3for loops
I think it will greater than that

Ответить
@munazzainamulhaque8863
@munazzainamulhaque8863 - 29.07.2020 20:42

So good explanation ...thanks!

Ответить
@weirdprogrammer415
@weirdprogrammer415 - 27.04.2021 13:33

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.

Ответить
@abbas.muzammil23
@abbas.muzammil23 - 16.05.2021 22:18

Space complexity?

Ответить
@damansharma5653
@damansharma5653 - 30.05.2021 04:27

Was a classic DNF problem, should have shown that. Binge watching your algos Playlist, good job.

Ответить
@anikkumarroy7403
@anikkumarroy7403 - 06.06.2021 15:15

Sir can we use bubble sort as well

Ответить
@akashsharma143
@akashsharma143 - 07.08.2021 14:16

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.

Ответить
@suchitrapal
@suchitrapal - 16.05.2022 08:26

Can we use Arrays.sort(a);

Ответить
@manasnath7680
@manasnath7680 - 26.05.2024 20:30

Thanks, now I got a clear picture.

Ответить
@jackdesparrow4783
@jackdesparrow4783 - 12.07.2024 08:34

How to get 0,2,1 from above array

Ответить