How to sort binary array containing only 0 and 1? If we have array containing decimal number then it is easy.This is generally asked question in any C++ interview. Problem is to sort an array containing only 0 and 1 as an element in O(n). Following algorithm will sort the array in ascending order.Here you go for the detailed program.

How to sort binary array in O(n).

void main()
{
	//int arr[] = {0,0,1,0,1,1,0,1,0,0};
	int arr[] = {1,1,1,0,1,1,1,1,1,1};
	int size = 10;
	int i,j = 0;

	for(i = 1;i<size;i++)
	{
		if(arr[j] == 0)
		{
			j++;   // increment the j till first 1 in the array
			continue;
		}
		if(arr[j] == 1 && arr[i] == 0) // if ith and jth elements are different then swap both
		{
			int temp = arr[i];
			arr[i] = arr[j];
			arr[j] = temp;
			j++;
		}
	}
       
        // display sorted array
	for(i = 0; i<size; i++)
		cout << arr[i] << "  ";

}

Hope this will be helpful.If you like our post. let us know.

The following two tabs change content below.
He is founder and CTO of Habilelabs.io. He senior software architect. He is guru of various Mobile and web technologies including Node.js, Angular.js, Meteor.js. He is founder member of habilelabs Pvt. Ltd.