We are given a sorted array and we want to rearrange the array in the form of {max, min, max-1, min+1, max-2, min+2.........}. So here is the code:
Output: {7,1,6,2,5,3,4}
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<iostream> | |
using namespace std; | |
void printArray(int arr[], int n); | |
void maxMin(int arr[], int n) { | |
int arr2[n]; | |
int mid = n/2; | |
for(int i = 0,j = n-1, k =0; i< mid, j>=mid, k<n; k++) { | |
if(k%2 != 0) { | |
arr2[k] = arr[i]; | |
i++; | |
} | |
else { | |
arr2[k] = arr[j], j-- ; | |
} | |
} | |
printArray(arr2, n); | |
} | |
void printArray(int arr[], int n) { | |
for(int i = 0; i< n; i++) { | |
cout<<arr[i]<<" "; | |
} | |
} | |
int main() { | |
int arr[] = {1,2,3,4,5,6,7}; | |
int n = sizeof(arr)/sizeof(arr[0]); | |
maxMin(arr, n); | |
return 0; | |
} |
No comments:
Post a Comment