Endrit Shabani
Endrit Shabani

Reputation: 337

Why this reverse array method isnt working?

I am trying to make a method to reverse an array, I don't know why it is not working?

When I said int[] arr = array, I want to do this so it will not be affected so I can use the elements for the second for loop and it should have elements {1,2,3,4,5,6} but when I use

for (int i=array.Length-1;i>array.Length/2;i--)
{
    array[i] = arr[array.Length - 1 - i];
}

In this case I have 6 elements so array.Length is 6 and since I started from array.Length-1 it must start from the last element and it must be array[5]=arr[6-1-5] which must be array[5]=arr[0] and arr[0] is 1 but I think it is getting it as 6, why?

Here is the complete code:

// ReverseArray method
static int [] ReverseArray(int [] array)
{
    int[] arr = array;
    for (int i=0; i<array.Length/2;i++)
    {
        array[i] = array[array.Length-1  - i];
    }
    for (int i=array.Length-1;i>array.Length/2;i--)
    {
        array[i] = arr[array.Length - 1 - i];
    }
    return array;
}

// Method for displaying elements of Array
static void DisplayArray(int [] array)
{
    int i;
    Console.Write("{");
    for (i = 0; i < array.Length-1; i++)
    {
        Console.Write(array[i] + ",");
    }
    Console.WriteLine(array[i] + "}");
}

static void Main(string[] args)
{
    int[] array = { 1, 2, 3, 4, 5 ,6};
    ReverseArray(array);
    DisplayArray(array);
    Console.ReadKey();
}

Upvotes: 3

Views: 162

Answers (2)

Ray Krungkaew
Ray Krungkaew

Reputation: 6965

I couldn't help myself but start to write a piece of code trying to solve it.

    int[] arr = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    arr = Reverse(arr).ToArray();

Here is the shorter way to achieve that.

    public IEnumerable<int> Reverse(int[] arr)
    {
        for (int i = arr.Length-1; i >= 0; i--)
        {
            yield return arr[i];
        }
    }

Upvotes: 6

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726499

Your reversal approach is invalid: rather than swapping elements at indexes i and array.Length-1 - i, your code copies the tail portion of the array onto the initial one, effectively "folding" the array onto itself.

You need to remove the second loop, and replace the assignment with a swap: make a temporary variable, store array[i], copy array[array.Length-1 - i], then write the temporary in its place.

Upvotes: 7

Related Questions