Convert array into Zig-Zag fashion in C++


In this tutorial, we will be discussing a program to convert an array into zig-zag fashion.

For this we will be provided with an array containing distinct elements. Our task is to rearrange the elements of the given array in a zig zag fashion with greater and smaller elements alternatively as compared to the previous element.

Example

 Live Demo

#include <iostream>
using namespace std;
//converting into zig-zag fashion
void convert_zigzag(int arr[], int n) {
   //flag denotes the greater or smaller relation
   bool flag = true;
   for (int i=0; i<=n-2; i++) {
      if (flag) {
         if (arr[i] > arr[i+1])
         swap(arr[i], arr[i+1]);
      } else {
         if (arr[i] < arr[i+1])
            swap(arr[i], arr[i+1]);
      }
      flag = !flag;
   }
}
int main() {
   int arr[] = {4, 3, 7, 8, 6, 2, 1};
   int n = sizeof(arr)/sizeof(arr[0]);
   convert_zigzag(arr, n);
   for (int i=0; i<n; i++)
      cout << arr[i] << " ";
   return 0;
}

Output

3 7 4 8 2 6 1
raja
Published on 16-Jan-2020 07:04:07
Advertisements