Reverse elements in an array

后端 未结 6 1896
既然无缘
既然无缘 2020-11-30 14:58

I setup an array and i would like to create a method that will return an array with the elements in reverse. e.g. if there are 10 slots then array1[9] = 6 so

6条回答
  •  余生分开走
    2020-11-30 15:44

    You can reverse an array by swapping elements from both ends of the array till you reach the middle.

    for(int start = 0, end = arr.Length - 1; start < arr.Length/2; start++, end--)
    {
         swap(arr[start], arr[end]);
    }
    

提交回复
热议问题