Problem 6-1

CSharp · Console

/Program.cs

// Write a program that rearranges the elements in integer array of size N so that all
// negative elements go first, then all zeroes, then all positives. 
using System;
					
public class Program
{
	public static void Main()
	{
		// Test
		int[] a = {1, -3, 5, 7, -9, 2, -4, 6, 8};
		partitioning(a, 0);
		printArray(a);
	}
	
	public static void partitioning(int[] a, int mid)
	{
		int s = 0, b = 0;
		
		// invariant: first s elements of array (a[0..s-1]) are smaller than mid and 
		//            last  b elements of array (a[a.Length - b .. a.Length - 1]) are equal or bigger than mid and
		//            s + b <= a.Length
		// limiter: s + b increases by 1 on each iteration and cannot exceed a.Length
		while (s + b != a.Length)
		{
			// s + b < a.Length
			if(a[s] < mid)
				s++;
			else if(a[a.Length - 1 - b] >= mid)
				b++;
			else
			{	// a[s] >= mid and a[a.Length - 1 - b] < mid
				swap(ref a[s], ref a[a.Length - 1 - b]);
				s++;
				b++;
			}
		}
		
		// a[0 .. s-1] < mid and a[a.Length - b .. a.Length - 1] >= mid and b == a.Length - s =>
		// a[0 .. s-1] < mid and a[s .. a.Length - 1] >= mid
	}
	
	public static void printArray(int[] a)
	{
		for(int i = 0; i <a.Length; ++i)
		{
			Console.Write(" " + a[i]);
		}
		Console.WriteLine();
	}
	
	public static void swap(ref int a, ref int b)
	{
		int temp = a;
		a = b;
		b = temp;
	}
}
;