Move zeros to the right with minimum swap in C#

You are given an integer array which contains some zeros. Move the zeros to the right side of the array with minimum number of swaps. The order of the original array can be destroyed.

class MoveZeros
{
static void Main(string[] args)
{
int[] arr = { 0, 2, 0, 4, 3, 0, 1, 5, 0 };

MoveZerosToRight(arr);
}

private static void MoveZerosToRight(int[] arr)
{
int start = 0, end = arr.Length – 1;
while (start <= end)
{
if (arr[start] == 0 && arr[end] != 0)
{
arr[start] = arr[end];
arr[end] = 0;
++start;
–end;
}
else
{
if (arr[start] != 0)
{
++start;
}

if (arr[end] == 0)
{
–end;
}
}
}

foreach (int num in arr)
{
Console.Write(num + “, “);
}
Console.ReadKey();
}
}

Advertisements

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