File tree Expand file tree Collapse file tree 1 file changed +27
-0
lines changed
Expand file tree Collapse file tree 1 file changed +27
-0
lines changed Original file line number Diff line number Diff line change 1+ def segregate0and1 (arr , size ): '''Time complexity is O(n)'''
2+ # Initialize left and right indexes
3+ left , right = 0 , size - 1
4+
5+ while left < right :
6+ # Increment left index while we see 0 at left
7+ while arr [left ] == 0 and left < right :
8+ left += 1
9+
10+ # Decrement right index while we see 1 at right
11+ while arr [right ] == 1 and left < right :
12+ right -= 1
13+
14+ # If left is smaller than right then there is a 1 at left
15+ # and a 0 at right. Exchange arr[left] and arr[right]
16+ if left < right :
17+ arr [left ] = 0 #instead of swap, we can just assign 0 and 1 here
18+ arr [right ] = 1
19+ left += 1 #since value at this index is now okay, we can inc/dec them
20+ right -= 1
21+
22+ return arr
23+
24+ arr = [0 , 1 , 0 , 1 , 1 , 1 ]
25+ arr_size = len (arr )
26+ print ("Array after segregation" )
27+ print (segregate0and1 (arr , arr_size ))
You can’t perform that action at this time.
0 commit comments