RSS

Simple array rotation example in C#

Tue, Dec 8, 2009

Inverview Tips, Programming, Tutorials

We’ve a solution for following frequently asked interview question. Here’s problem statement “Implement the following function, RotateArray, which takes as its input an array of unique integers that has been sorted in ascending order, then rotated by an unknown amount X where 0 <= X <= (arrayLength - 1). An array rotation by amount X moves every element array[i] to array[(i + X) % arrayLength]. RotateArray discovers and returns X by examining the array. You should be able to do this in less than linear time."

Signature of method would be:

1
public int[] RotateArray(int[] a, int X);

Here’s implementation:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/// <summary>
/// Rotates sorted array.
/// </summary>
/// <param name="a">integer array</param>
/// <param name="X">rotation index</param>
/// <returns></returns>
public int[] RotateArray(int[] a, int X)
{
	int[] output = new int[a.Length];
	int j;
 
	for (int i = 0; i < a.Length; i++)
	{
		j = (i + X) % a.Length;
		if (j < 0)
		{
			j += a.Length;
		}
		output[j] = a[i];
	}
	return output;
}

Testing this method:

1
2
3
4
5
6
7
8
static void Main(string[] args)
{
	int[] a = RotateArray(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }, 3);
	foreach (int i in a)
	{
		Console.Write(i + " ");
	}
}

OUTPUT:

7 8 9 1 2 3 4 5 6 //input: 1 2 3 4 5 6 7 8 9
Sharing ~ Helping Other:
  • Print
  • email
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • BlinkList
  • DZone
  • Slashdot
  • YahooMyWeb
  • StumbleUpon
  • Live
  • IndianPad
  • DotNetKicks
  • Technorati

Related Posts:

, , ,

This post was written by:

eXclusiveMinds - who has written 498 posts on eXclusiveMinds.


Contact the author

1 Comments For This Post

  1. chota Says:

    More Efficient Algorithms for this:
    Input: 1 2 3 4 5 6 7 8 9 (arr)
    Output: 7 8 9 1 2 3 4 5 6
    rotate by: 6 (n)

    public int[] RotateArray(int[] arr, int X)
    {
    Reverse(arr, 0, n);
    Reverse(arr, n+1, arr.Length-1);
    Reverse(arr, 0, arr.Length-1);
    return arr;
    }

    //Implement the method to reverse the array
    public int[] Reverse(int[] a, int lower, int upper)
    {
    for(int i= lower; i<upper; i++;upper–)
    {
    int temp = a[i];
    a[i] = a[upper];
    a[upper] = temp;
    return a;
    }
    }

Leave a Reply

You must be logged in to post a comment.