Print array elements in alternatively increasing and decreasing order in C++

C++Server Side ProgrammingProgramming

In this problem, we are given an array of number and we have to print the elements of the array in alternatively increasing and decreasing order while printing. The alternative order will be in such a way that 1st two elements are in increasing order and then the next three elements are in decreasing order again next four are in ascending order.

Let’s take an example to understand the problem better,

Input  : {1, 4, 0, 2, 7, 9, 3}
Output : 0 1 9 7 4 2 3

Explanation − the array in increasing order of elements is 0 1 2 3 4 7 9. The first 2 elements are 0 1. The last 3 elements are 9 7 4. Next 4 four elements are 2 3 (we could take 4 elements but there are only 2 in the array).

To solve this problem, we will first sort the array in ascending order. Now, we will use two pointers one for printing elements from start and one for printing element for the end. We will also use one flag element to check if the print is to be done from the start or from the end.

Algorithm

Step 1 : Sort elements of the array.
Step 2 : Initialise left = 0 , right = n-1 , flag = 2.
Step 3 : while l is less than equal to r. Do :
Step 4 : If flag%2 == 0. Do :
   Step 4.1 : loop from i = left to left + flag. And print arr[i].
   Step 4.2 : update left = i ; flag ++;
Step 5 : else. Do :
   Step 5.1 : loop from i = right to right - flag. And print arr[i].
   Step 5.2 : update right = i and flag ++.
Step 6 : EXIT

Example

Now, let’s create a program to illustrate the working of this algorithm.

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void printAlternateSeq(int arr[], int n){
   sort(arr, arr + n);
   int left = 0, right = n - 1, flag = 2, i;
   while (left <= right) {
      if (flag%2 == 0) {
         for (i = left; i < left + flag && i <= right; i++)
         cout<<arr[i]<<" ";
         left = i;
      } else {
         for (i = right; i > right - flag && i >= left; i--)
            cout<<arr[i]<<" ";
         right = i;
      }
      flag++;
   }
}
int main(){
   int n = 6;
   int arr[] = {23, 45, 78, 32, 89, 10 };
   printAlternateSeq(arr, n);
   return 0;
}

Output

10 23 89 78 45 32
raja
Published on 03-Jan-2020 14:17:28
Advertisements