...

/

Solution: Arrange a Binary Array

Solution: Arrange a Binary Array

Explore various approaches to solving the problem of sorting a binary array in detail.

Solution 1: Bubble sort

using System;
class Program
{
/// <summary>
/// A method to sort a binary array.
/// </summary>
/// <param name="arr">An array containing binary numbers.</param>
/// <returns>A sorted binary array.</returns>
public static int[] SortBinaryArray(int[] arr)
{
int size = arr.Length; // Store the size of array
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size - i - 1; j++)
{
// traverse the list from 0 to size - i - 1
// Swap if the current element is greater than the next element
if (arr[j] > arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
return arr;
}
// Driver to test above code
static void Main()
{
int[] arr = { 1, 0, 1, 0, 1, 0, 1, 0 };
int[] result = SortBinaryArray(arr);
Console.WriteLine("[" + string.Join(", ", result) + "]");
}
}

Explanation

The most obvious solution to this problem is the bubble sort algorithm. All the elements in the list are either zeros or ones. Sorting the elements in ascending order with the help of the bubble sort algorithm will shift all the zeros to the left and all the ones to the right.

Time complexity

...