Why does this inverse array method not work?

I am trying to make a method to modify an array, I do not know why it does not work?

When I said int[] arr = array, I want to do this so that it is not affected, so I can use elements for the second cycle for, 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.Lengthis 6, and as I started with array.Length-1, it must begin with the last element, and it should be array[5]=arr[6-1-5], that should be array[5]=arr[0]and arr[0]is equal to 1, but I think it is obtained 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();
}
+4
source share
2 answers

: , i array.Length-1 - i, , "" .

swap: , array[i], array[array.Length-1 - i], .

+7

, , .

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

.

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

Source: https://habr.com/ru/post/1692584/


All Articles