Programming Alogorithm Series: Reverse an Array
Reverse an Array is one of the most common programming algorithm questions that is asked in many tech interviews. Here is a quick way with sample code:
using System;
System; namespace ReverseArray
{
/// <summary>
/// Reverse an Array quickly
/// </summary>
ReverseArray
{
/// <summary>
/// Reverse an Array quickly
/// </summary> class Program
{
static void Main(string[] args)
{
int[] array = new int[] {1,2,3,4,5,6,7,8,9};
// Print before reverse
for (int i = 0; i < array.Length; i++)
{
Console.Write(array[i]);
}
Console.ReadLine();
class Program
{
static void Main(string[] args)
{
int[] array = new int[] {1,2,3,4,5,6,7,8,9};
// Print before reverse
for (int i = 0; i < array.Length; i++)
{
Console.Write(array[i]);
}
Console.ReadLine();
ReverseArrayClass.ReverseArray(array);
// Print after reverse
for (int i = 0; i < array.Length; i++)
{
Console.Write(array[i]);
}
Console.ReadLine();
}
}
/// <summary>
/// Array Reverse Alogorithm
/// </summary>
class ReverseArrayClass
{
public static void ReverseArray(int[] array)
{
int tempInt;
for (int i=0; i<(array.Length/2); i++)
{
tempInt = array[i];
array[i] = array[array.Length -i-1];
array[array.Length -i-1] = tempInt;
}
}
}
}
class ReverseArrayClass
{
public static void ReverseArray(int[] array)
{
int tempInt;
for (int i=0; i<(array.Length/2); i++)
{
tempInt = array[i];
array[i] = array[array.Length -i-1];
array[array.Length -i-1] = tempInt;
}
}
}
}