We are given an array of 0s and 1s in random order. Segregate 0s on left side and 1s on right side of the array. Traverse array only once.
Input : arr = [0, 1, 0, 1, 0, 0, 1, 1, 1, 0] Output : arr = [0, 0, 0, 0, 0, 1, 1, 1, 1, 1] Input : arr = [1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1] Output : arr = [0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1]
We have already discussed a solution Segregate 0s and 1s in an array
In this post, a new solution is discussed.
Step 1 : Here we can take two pointers type0 (for element 0) starting from beginning (index = 0) and type1 (for element 1) starting from end index.
Step 2: We intend to put 1 to the right side of the array. Once we have done this then 0 will definitely towards left side of array to achieve this we do following.
We compare elements at index type0
1) if this is 1 then this should be moved to right side so we need to swap this with index type1 once swapped we are sure that element at index type1 is ‘1’ so we need to decrement index type1
2) else it will be 0 then we need to simple increment index type0
Time Complexity : O(n)
0 0 0 1 1 1 1 1 1 1 1
- Sort array after converting elements to their squares
- Sort an almost sorted array where only two elements are swapped
- Sort elements of array whose modulo with K yields P
- Sort elements of the array that occurs in between multiples of K
- Sort the linked list in the order of elements appearing in the array
- Insertion sort to sort even and odd positioned elements in different orders
- Bucket Sort To Sort an Array with Negative Numbers
- Program to sort an array of strings using Selection Sort
- Sum of elements in 1st array such that number of elements less than or equal to them in 2nd array is maximum
- Sort elements by frequency | Set 2
- Sort elements by frequency | Set 1
- Sort an array where a subarray of a sorted array is in reverse order
- Insertion Sort by Swapping Elements
- Sort elements by frequency | Set 5 (using Java Map)
- Sort even and odd placed elements in increasing order
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.