To begin with, do a linear search to find the first occurrence of the value that you want to make the first element:
// value contains the value to find.
int skip;
for (int i = 0; i < array.Length; i++)
{
if (array[i] == value)
{
skip = i;
break;
}
}
// skip contains the index of the element to put at the front.
// Equivalently, it is the number of items to skip.
// (I chose this name for it because it makes the subtractions
// in the Array.Copy implementation more intuitive.)
Do you want to change the actual array? Then do what Thorsten Dittmar suggests:
int[] array = new int[] { 2, 3, 6, 1, 7, 6 };
int[] result = new int[array.Length];
int skip = 2; // So that array[skip] will be result[0] at the end
Array.Copy(array, skip, result, 0, array.Length - skip);
Array.Copy(array, 0, result, array.Length - skip, skip);
Do you want to just view the array in the new order, without doing anything else? Then index it like so:
array[(i + skip) % array.Length] // Instead of array[i]
Edit: Just for laughs, an implementation of Jon Skeet's suggestion to implement the copy while using only a single buffer value (sourceValue
):
// GCD gives the greatest common divisor
int gcd = GCD(array.Length, skip);
// period is the length of the permutation cycles in our rotation.
int period = array.Length / gcd;
int max = array.Length / period;
for (int i = 0; i < max; i++)
{
int sourceIndex = i;
int sourceValue = array[sourceIndex];
for (int n = 1; n <= period; n++)
{
int destinationIndex = (sourceIndex + array.Length - skip) % array.Length;
int temp = array[destinationIndex];
array[destinationIndex] = sourceValue;
sourceValue = temp;
sourceIndex = destinationIndex;
}
}