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
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Find Kth element in an array containing odd elements first and then even elements
- Comparison among Bubble Sort, Selection Sort and Insertion Sort
- Add elements in start to sort the array | Variation of Stalin Sort
- Sort Linked List containing values from 1 to N
- Find four missing numbers in an array containing elements from 1 to N
- Insertion sort to sort even and odd positioned elements in different orders
- Sort an almost sorted array where only two elements are swapped
- Sort elements of an array in increasing order of absolute difference of adjacent elements
- Number of subsequences of maximum length K containing no repeated elements
- Bucket Sort To Sort an Array with Negative Numbers
- Program to sort an array of strings using Selection Sort
- Sort an Array which contain 1 to N values in O(N) using Cycle Sort
- Sort an array by swapping elements of different type specified by another array
- Find all elements in array which have at-least two greater elements
- Why Quick Sort preferred for Arrays and Merge Sort for Linked Lists?
- Odd-Even Sort / Brick Sort
- Sort all even numbers in ascending order and then sort all odd numbers in descending order
- Serial Sort v/s Parallel Sort in Java
- C/C++ Program for Odd-Even Sort / Brick Sort
- Java Program for Odd-Even Sort / Brick Sort
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.