Posts Convert array into Zig-Zag fashion (geeksforgeeks - SDE Sheet)
Post
Cancel

Convert array into Zig-Zag fashion (geeksforgeeks - SDE Sheet)

PROBLEM DESCRIPTION

Given an array arr of distinct elements of size N, the task is to rearrange the elements of the array in a zig-zag fashion so that the converted array should be in the below form:

1
arr[0] < arr[1]  > arr[2] < arr[3] > arr[4] < . . . . arr[n-2] < arr[n-1] > arr[n].

NOTE: If your transformation is correct, the output will be 1 else the output will be 0.

geeksforgeeks

SOLUTION

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution{

    public void zigZag(int a[], int n){

        Arrays.sort(a);

        for(int i=1; i+1<n; i+=2){
            swap(a, i, i+1);
        }

    }

    public void swap(int a[], int i, int j){
        int t = a[i];
        a[i] = a[j];
        a[j] = t;
    }

}
This post is licensed under CC BY 4.0 by the author.