Rearrange an array in maximum minimum form | method -1

Question - 
Given a sorted array of positive integers, rearrange the array alternately i.e first element should be maximum value, second minimum value, third second max, fourth second min and so on.
Example - 

Input: arr[] = {1, 2, 3, 4, 5, 6, 7}
Output: arr[] = {7, 1, 6, 2, 5, 3, 4}

Input: arr[] = {1, 2, 3, 4, 5, 6}
Output: arr[] = {6, 1, 5, 2, 4, 3}


Approach - 

first we create two variable named start and end which is equal to 0 and n-1.

we print last element and decrease en and then print first element and increase start and we print like this until start is not less than or equal to end.


Implementation - 

// print in maxima and minima form if array is sorted

#include<iostream>

using namespace std;

void printmaximaminina(int arr[],int n)

{

    int start=0,end=n-1;

    for(int i=0;start<=end;i++){

       if(i%2==0)

       cout<<arr[end--]<<" ";

       else 

       cout<<arr[start++]<<" ";


    }


}

int main()

{

    int n;

    cout<<"Enter the number of elements : ";cin>>n;

    int arr[n];

    for(int i=0;i<n;i++)

        cin>>arr[i];


    printmaximaminina(arr,n);

    return 0;

}

Time complexity - O(n)

Comments