Given an array of sizes n and we need to reverse all array elements in place and print the reverse array.
Note: The task is to reverse the array in place so that when we print the same array the array elements should be in reverse order.
{2, 4, 8, 1, 9} --- Reverse --- {9, 1, 8, 4, 2}
Example:
Input: arr[] = {9, 2, 7, 3, 10} Output: arr[] = {10, 3, 7, 2, 9}
Approach: Using Iterative way (Brute Force)
Steps to solve the problem:
- Declare two variables, start = 0 and end = n-1 where n is the size of the given array.
- Run a while loop and keep swapping arr[start] and arr[end] and after each swap increment the value of start = start + 1 and decrement the value of end = end - 1.
- Break the loop condition as soon as start >= end.
C++ code Implementation:
//C++ code to reverse the array elements #include<bits/stdc++.h> using namespace std; //function to reverse array void reverseArray(int arr[], int n){ int start = 0, end = n - 1; while(start < end){ int temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; start++; end--; } } int main(){ int arr[] = {9, 2, 7, 3, 10}; //size of given array int n = sizeof(arr)/sizeof(arr[0]); reverseArray(arr, n); for(int i = 0; i < n; i++){ cout<<arr[i]<<" "; } return 0; }
10, 3, 7, 2, 9
- Time Complexity: O(n)
- Space Complexity: (1)
Also see:
No comments:
Post a Comment