Java Program of Zig zag Array

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:

Main.java

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);
    }
}

Recommended:

  1. Array square
  2. Generate number using odd digits
  3. Alternate Number Difference
  4. Next Greatest number
  5. Mark Comparison
  6. Print the characters in descending order
  7. Vowels in a fishBowl
  8. Least offer
  9. Ascending and descending order
  10. Mail Domain
  11. Count repeating words
  12. Sentence – Convert to upper and lower
  13. Count consecutive repeating characters
  14. Zig zag Array
  15. Pass and Fail Count
  16. Search a Course
  17. Average and Grade Calculation
  18. String – Find and replace the character (first occurrence)
  19. Sort the first and second half of an array
  20. Retail Shop
  21. Palindrome
  22. Numerology
  23. InitCap
  24. Array Compatiblilty
  25. Sum of the maximum and the minimum element
  26. String Concatenation
  27. Find Average Age
  28. Login
  29.  

Leave a Comment

Your email address will not be published. Required fields are marked *

x