Zig zag Array Program in java

In this post, we will learn Zig zag Array Program in java Programming language.

Question:

Write a program to arrange the elements in the array so that it satisfies the below condition.

a<b>c<d>e<f…….

[Input format: The First input refers to the no of elements in the array and the next is the series of elements in the array]

Sample Input 1:

6

1

2

3

4

5

6

Sample Output 1:

1

3

2

5

4

6

Sample Input 2:

7

14

7

1

3

2

6

4

Sample Output 2:

7

14

1

3

2

6

4

CODE:

import java.util.*;
public class Main
{
    void zigzag(int[] arr)
    {
        boolean flag=true;
        int temp=0;
        for(int i=0;i<(arr.length-1);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;
        }
        for(int i=0;i<arr.length;i++)
        {
            System.out.println(arr[i]);
        }
    }
    public static void main (String[] args)
    {
        Scanner sc=new Scanner(System.in);
        int n=sc.nextInt();
        int arr[]=new int[n];
        int len=arr.length;
        for(int i=0;i<len;i++)
        {
            arr[i]=sc.nextInt();
        }
        Main obj=new Main();
        obj.zigzag(arr);
    }
}
Next:
  1. Pass and Fail Count
  2. Search a Course
  3. Average and Grade Calculation
Sharing Is Caring

Leave a Comment