Home >Backend Development >C++ >Rearrange an array so that every odd-indexed element is greater than its previous element
We have an array of positive integer type, assumed to be arr[], with any size. The task is to rearrange the array so that all elements at odd index positions have greater values than elements at even index positions, and print the result.
Input − int arr[] = {2, 1, 5, 4, 3, 7, 8}
Output − Array before sorting: 2 1 5 4 3 7 8 Rearrange the array so that every odd-indexed element is greater than its previous element: 1 4 2 5 3 8 7
Explanation - We are given an array of integers of size 7 . Now, if the element at even index is larger, we will swap the element at even index and the element at odd index
Arr[0] > arr[1] = call swap = {1, 2, 5, 4, 3, 7, 8} Arr[2] > arr[3] = call swap = {1, 2, 4, 5, 3, 7, 8} Arr[6] > arr[5] = call swap = {1, 2, 4, 5, 3, 8, 7} Arr[2] > arr[1] = call swap = {1, 4, 2, 5, 3, 8, 7}
input− int arr[] = {3, 2, 6, 9}
Output− Array before sorting: 3 2 6 9 Rearrangement of an array such that every odd indexed element is greater than it previous is: 2 3 6 9
Explanation − we are given an integer array of size 4. Now, we will swap the elements at even index with the elements at odd index if even indexed elements are greater i.e. Arr[0] > arr[1] = call swap = {2, 3, 6, 9}. No need to further call the swap method as all the elements at positions satisfies the conditions
Input an array of integer type elements and calculate the size of an array .
#include <iostream> using namespace std; void Rearrangement(int arr[], int size){ int ptr = size - 1; for(int i = 0; i < ptr; i = i+2){ if(arr[i] > arr[i+1]){ swap(arr[i], arr[i+1]); } } if(size & 1){ for(int i = ptr; i > 0; i = i-2){ if(arr[i] > arr[i-1]){ swap(arr[i], arr[i-1]); } } } } int main(){ //input an array int arr[] = {2, 1, 5, 4, 3, 7, 8}; int size = sizeof(arr) / sizeof(arr[0]); //print the original Array cout<<"Array before Arrangement: "; for (int i = 0; i < size; i++){ cout << arr[i] << " "; } //calling the function to rearrange the array Rearrangement(arr, size); //print the array after rearranging the values cout<<"\nRearrangement of an array such that every odd indexed element is greater than it previous is: "; for(int i = 0; i < size; i++){ cout<< arr[i] << " "; } return 0; }OutputIf we run the above code, the following output will be generated
Array before Arrangement: 2 1 5 4 3 7 8 Rearrangement of an array such that every odd indexed element is greater than it previous is: 1 4 2 5 3 8 7
The above is the detailed content of Rearrange an array so that every odd-indexed element is greater than its previous element. For more information, please follow other related articles on the PHP Chinese website!