How to print an array when first element is first max and second element is first min and so on in C++

1 Answer

0 votes
#include <iostream>
#include <algorithm>

void print_first_max_second_min(int arr[], int size) { 
    std::sort(arr, arr + size); 

    int i = 0, j = size - 1; 
    while (i < j) { 
        std::cout << arr[j--] << " "; 
        std::cout << arr[i++] << " "; 
    } 
  
    if (size % 2 != 0) 
        std::cout << arr[i]; 
} 

int main() 
{ 
    int arr[] = {13, 5, 2, 10, 4, 9, 7, 8, 559}; 
    int size = sizeof(arr)/sizeof(arr[0]); 
    
    print_first_max_second_min(arr, size); 
    
    return 0; 
} 




/*
run:

559 2 13 4 10 5 9 7 8

*/

 

 



answered Dec 8, 2021 by avibootz
...