How to Reverse an Array

Recently I went for a job interview, and I was asked to write an algorithm to reverse an array, and yes obviously without using the Array.Reverse() method… 😉

It seemed pretty simple at the beginning, but honestly I struggled a bit in the middle, but after few failed attempts I figured it out a bit for that moment. So I came back home and reattempted it by myself… 🙂

So as usual here I am sharing the code with you guys if any of you ever go through such a situation.. 😀 hope this might come in handy…

using System;
using System.Collections.Generic;
					
public class Program
{
	public static void Main()
	{
		//Reversing a List

		List<int> list = new List<int>();
		list.Add(1);
		list.Add(2);
		list.Add(3);
		list.Add(4);
		list.Add(5);
				
		for(int l=0; l<list.Count; l++)
		{
			Console.Write(list[l]);
		}
		
		Console.WriteLine("\n");
				
		int i = 0;
		while(i < list.Count/2)
		{
			int x = list[i];
			int y = list[(list.Count - i)-1];
			
			Console.Write("Reversing - ");
			Console.Write(list[i]);
			Console.Write(" - ");
			Console.Write(list[(list.Count - i)-1]);
			Console.Write("\n");
									
			list[i] = y;
			list[(list.Count - i)-1] = x;	
			
			i++;
		}
		
		Console.WriteLine("\n");
		
		for(int l=0; l<list.Count; l++)
		{
			Console.Write(list[l]);
		}
	}
}

 

Just to share something I learned…
Never rush for a solution just because it looks simple… First take your time, analyse the solution from top to bottom and then go for it.. 😉 or else you might struggle in the middle like I did, which would leave a black mark at your job interview…

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