Segregate 0s and 1s in an array

using System;

using System.Collections.Generic;

using System.Collections;

using System.Linq;

using System.Text;

 

namespace ConsoleApplication1

{

    class Program

    {

        static void Main(string[] args)

        {

            int[] intArray = { 0, 1, 0, 1, 0, 0, 1, 1, 1, 0 };

            Console.WriteLine("Array before segregation: ");

            for (int i = 0; i < intArray.Length; i++)

            {

                Console.Write(intArray[i] + " ");

            }

            Console.WriteLine();

            Console.WriteLine("Array after segregation: ");

            intArray = Segregate(intArray);

            for (int i = 0; i < intArray.Length; i++)

            {

                Console.Write(intArray[i] + " ");

            }

            Console.WriteLine();

        }

        public static int[] Segregate(int[] intArray)

        {

            int start = 0;

            int end = intArray.Length – 1;

            while (start < end)

            {

                while (intArray[start] == 0 && start < end)

                {

                    start++;

                }

                while (intArray[end] == 1 && start < end)

                {

                    end–;

                }

                if (start < end)

                {

                    intArray[start] = 0;

                    intArray[end] = 1;

                    start++;

                    end–;

                }

            }

            return intArray;

        }

    }

}
 
Array before segregation:
0 1 0 1 0 0 1 1 1 0
Array after segregation:
0 0 0 0 0 1 1 1 1 1
Press any key to continue . . .
Advertisements
This entry was posted in Information Technology. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s