Spread the post

Segregate 0s and 1s in an array

Given an array, and there are contain data in 0s and 1s in un-sorted form. Our goal is to arrange this 0s and 1s data in separate group.

Example:

Stack Areamainarray1 [0] 1 [1] 0 [2] 0 [3] 1 [4] 0 [5] 1 [6] 0 [7] 1 [8] 0array2 [0] 1 [1] 1 [2] 0 [3] 0 [4] 1 [5] 1 [6] 0 [7] 0 [8] 1Before Stack Areamainarray1 [0] 1 [1] 1 [2] 1 [3] 1 [4] 0 [5] 0 [6] 0 [7] 0 [8] 0array2 [0] 1 [1] 1 [2] 1 [3] 1 [4] 1 [5] 0 [6] 0 [7] 0 [8] 0After

Given a two method to solve this problem.

1) Simplest method : In this method count all number of 1's. and put all 1's at beginning of array and remaining are 0s. time complexity is O(n).

This function are separating 1s and 0s.

2) Special method : This method use two integer variable start_index and end_index. start_index are initialize 0 and end_index are initialize (size of array -1). Use only one while loop.

This function are separating 1s and 0s.


Program

Output


Code execution process.

Stack Areamainarray1 [0] 1 [1] 1 [2] 1 [3] 1 [4] 0 [5] 0 [6] 0 [7] 0 [8] 0array2 [0] 1 [1] 1 [2] 1 [3] 1 [4] 1 [5] 0 [6] 0 [7] 0 [8] 0size (int) =9show_arrayarray_data(pointer)index (int) =0size (int) =9

Try it Yourself

Spread the post

Recommended Posts: