Sort the given unordered set of Binary digits

In this problem, we shall be given an unordered set of binary digits (0s and 1s) and we are expected to sort all the digits into ascending order. For example, If the given array of digits are [1,0,1,1,0,0,1,1,1,1] the output should be [0,0,0,1,1,1,1,1,1,1].

If we observe, the above question is a typical sorting program in which the given unordered set of numbers need to be sorted in some order. Although the numbers in this case can only be 0 or 1.

Generally, people tend to solve this using two for-loops, where the first loop runs from the first index to the end, while the second loop comparing each element from the index of the first loop with the second. But I’d want to avoid that approach, since it results in higher time complexity.

Instead, let’s do this in a sort-algorithm kind of approach where we place two pointers low and high representing the two ends of the set. In a single loop, we move both the pointers in the opposite direction and compare the elements under the current position of these indexes and swap the values if they’re in incorrect positions.

Because this question works on binary digits, its common sense that all 0s reside on the left side (represented by low) and the 1s reside on the right side (represented by high).

The logic looks like below:

Approach:

#input: [1,0,0,1,0,0,1,1,0,1]#
#output: [0,0,0,0,0,1,1,1,1,1]#

declare low, high
set low = 0 (to first index of the which always represents 0)
set high = len(input) - 1 (to last index which always represents 1)
loop till low and high collide (low < high)
if element at low index is 0, 
  increment low since its already at expected place
else if element at hight is 1, 
  decrement high since its already at expected place
else 
  swap the bits on both the places 
  and change counters for both low and high

Code in C#:

    public class BinarySort
    {
        public void SortBinary(int[] arrayOfBits)
        {
            int low = 0, high = arrayOfBits.Length - 1;

            while (low < high)
            {
                if (arrayOfBits[low] == 0)
                    low++;
                else if (arrayOfBits[high] == 1)
                    high--;
                else
                {
                    int swap = arrayOfBits[low];
                    arrayOfBits[low] = arrayOfBits[high];
                    arrayOfBits[high] = swap;
                    low++; high--;
                }
            }

            Console.WriteLine(String.Join(",", arrayOfBits));
        }
    }

Buy Me A Coffee

Found this article helpful? Please consider supporting!

Ram
Ram

I'm a full-stack developer and a software enthusiast who likes to play around with cloud and tech stack out of curiosity. You can connect with me on Medium, Twitter or LinkedIn.

Leave a Reply

Your email address will not be published. Required fields are marked *