We get a sorted array. We need to arrange this array in the largest and smallest form, that is, the first element is the largest element, the second element is the smallest element, the third element is the second largest element, and the fourth element is the second smallest element. And so on, for example -
Input : arr[ ] = { 10, 20, 30, 40, 50, 60 } Output : { 60, 10, 50, 20, 40, 30 } Explanation : array is rearranged in the form { 1st max, 1st min, 2nd max, 2nd min, 3rd max, 3rd min } Input : arr [ ] = { 15, 17, 19, 23, 36, 67, 69 } Output : { 69, 15, 67, 17, 36, 19, 23 }
There is a way to rearrange the array in maximum and minimum form -
There is a way to rearrange the array in maximum and minimum Minimum form rearranges array form -
Use two variables, min and max, here will point to the largest and smallest elements and create a new empty array of the same size to store the re-arrangement Arranged array. Now iterate over the array and if the iterated element is at an even index, add arr[max] elements to the empty array and decrement max by 1. If the element is at an odd index, add arr[min] elements to the empty array and increment min by 1. Do this until max is less than min.
#include <bits/stdc++.h> using namespace std; int main () { int arr[] = { 1, 2, 3, 4, 5, 6 }; int n = sizeof (arr) / sizeof (arr[0]); // creating a new array to store the rearranged array. int final[n]; // pointing variables to initial and final element index. int min = 0, max = n - 1; int count = 0; // iterating over the array until max is less than or equals to max. for (int i = 0; min <= max; i++) { // if count is even then store max index element if (count % 2 == 0) { final[i] = arr[max]; max--; } // store min index element else { final[i] = arr[min]; min++; } count++; } // printing the final rearranged array. for (int i = 0; i < n; i++) cout << final[ i ] << " "; return 0; }
6 1 5 2 4 3
In this article, we discussed the solution to rearrange the given array into max-min form. We discuss approaches to the solution and solve it with an optimistic solution with time complexity O(n). We also wrote a C program for this. Likewise, we can write this program in any other language like C, Java, Python, etc. We hope this article was helpful to you.
The above is the detailed content of Rearrange array into max-min form using C++. For more information, please follow other related articles on the PHP Chinese website!