How to segregate all 0 on left side and all 1 on right side of a given array of 0 and 1 in C#

1 Answer

0 votes
using System;

class Program
{
    static void Main() {
        int[] arr= {1, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0};
        int left = 0, right = arr.Length - 1;
  
        while (left < right) {
            while (arr[left] == 0 && left < right)
               left++; 
   
            while (arr[right] == 1 && left < right)
                right--;
   
            if (left < right) {
                arr[left] = 0;
                arr[right] = 1;
                left++;
                right--;
            }
        }
        Console.Write(string.Join(", ", arr));
    }
}
 
 
 
/*
run:
   
0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1
   
*/

 



answered Nov 20, 2021 by avibootz
edited Nov 20, 2021 by avibootz
...