Array into Zigzag Fashion | Convert the given array into zigzag pattern

Printing an array into Zigzag fashion is discussed here. Suppose you were given an array of integers, and you are told to sort the integers in a ‘zig-zag’ pattern. In general, in a zig-zag pattern, the first integer is less than the second integer, which is greater than the third integer, which is less than the fourth integer, and so on. Hence, the converted array should be in the form of e1 < e2 > e3 < e4 > e5 < e6.

Test cases:

Input:
7
4 3 7 8 6 2 1

Output:
3 7 4 8 2 6 1

Input:
4
1 4 3 2

Output:
1 4 2 3

Array into zigzag pattern

// C++ code to display array into Zigzag fashion

#include
void swap(int *x, int *y)
{
int temp = *x;
*x = *y;
*y = temp;
}
void zig_zag_fashion(int arr[], int n)
{
int flag = 1;
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 n;
printf(“\nEnter the number of elements : ” );
scanf(“%d”, &n);
int arr[n], i;
printf(“\nInput the array elements : “);
for(i=0; i<n; i++)
scanf(“%d”, &arr[i]);
printf(“\nZigzag pattern of the array : “);
zig_zag_fashion(arr, n);
for (int i=0; i<n; i++)
printf(“%d “, arr[i]);
printf(“\n”);
return 0;
}

// C code to display array into Zigzag fashion

#include
using namespace std;
void swap(int *x, int *y)
{
int temp = *x;
*x = *y;
*y = temp;
}
void zig_zag_fashion(int arr[], int n)
{
int flag = 1;
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 n;
cout << “\nEnter the number of elements : ” ;
cin >> n;
int arr[n], i;
cout << “\nInput the array elements : “;
for(i=0; i<n; i++)
cin >> arr[i];
cout << “\nZigzag pattern of the array : “;
zig_zag_fashion(arr, n);
for (int i=0; i<n; i++)
cout << arr[i] << ” “;
cout << endl;
return 0;
}

// Java code to display array into Zigzag fashion

import java.util.Arrays;

class Test
{
static int arr[] = new int[]{1,2,3,4,5,6,7};

static void zigZag()
{

boolean flag = true;

int temp =0;

for (int i=0; i<=arr.length-2; i++)
{
if (flag)
{
if (arr[i] > arr[i+1])
{
temp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = temp;
}

}
else
{

if (arr[i] < arr[i+1])
{
temp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = temp;
}
}
flag = !flag;
}
}

public static void main(String[] args)
{
zigZag();
System.out.println(Arrays.toString(arr));
}
}

// Python code to display array into Zigzag fashion

def zigZag(arr, n):
flag = True
for i in range(n-1):
if flag is True:
if arr[i] > arr[i+1]:
arr[i],arr[i+1] = arr[i+1],arr[i]
else:
if arr[i] < arr[i+1]:
arr[i],arr[i+1] = arr[i+1],arr[i]
flag = bool(1 – flag)
print(arr)

arr = [1,2,3,4,5,6,7]
n = len(arr)
zigZag(arr, n)

array into zigzag