Input: arr = [1,2,3,4,5,6,7,8]
Output: arr = [8,7,6,5,4,3,2,1]
Using technique of swapping two numbers without using extra space can work here.
static void Main(string[] args) { int[] arr = new int[] { 1, 2, 3, 4, 5, 6, 7, 8 }; for (int i = 0; i < arr.Length / 2; i++) { // In first iteration // arr[0] = 1+8 = 9 arr[i] += arr[arr.Length - i - 1]; // arr[7] = 9-8 = 1 arr[arr.Length - i - 1] = arr[i] - arr[arr.Length - i - 1]; // arr[0] = 9-1 = 8 arr[i] = arr[i] - arr[arr.Length - i - 1]; } foreach (int element in arr) Console.WriteLine(element); }
Output:
8
7
6
5
4
3
2
1
Answers:
Using technique of swapping two numbers without using extra space can work here.
Output:
8
7
6
5
4
3
2
1