- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
#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
Advertisements