×

Zigzag Array in Java

In this tutorial, we discuss, what is zigzag array and its example. Even we will create the java program. In this program, we convert the simple array into a zigzag array.

What is a Zigzag Array in Java?

Java has supported another type of array called a zigzag array. Zigzag array means a two-dimensional(2-D) array in which rows are already fixed and then different numbers of columns are fixed for each row.

int[][]a= new int[5][];
a[0]= new int[5];
a[1]= new int[2];
a[2]= new int[3];
a[3]= new int[1];
a[4]= new int[2]; 
Zigzag Array in Java

If there are no three consecutive elements in either increasing or decreasingorder in an array, it is said to be a zigzag array. That is to say, if the array contains three elements (say, ai, ai+1, ai+2), The array is not in a zigzag pattern. Because ai ai+1 ai+2 or ai > ai+1 > ai+2.

As a result, the condition can be symbolically represented as follows:

a <b> c < b > c < d > f 

The elements of the array are a, b, c, d, e, and f.

In a nutshell, array elements must alternately follow the less than (<) and greater than (>) orders. Every element has a larger or lesser value than its nearby.

There are two ways that can be used:

Method 1: A Simple Solution

  1. To begin, shorten the array that has been provided.
  2. The first element should be fixed.
  3. Swap the remaining parts in pairs after that. It denotes that you should swap a[1] and a[2], a[3] and a[4], and so forth.

Because no more space is required, the complexity of the aforementioned solution will be O(n log n) and the complexity of space will be O(1).

Method 2: A Cost-Effective Solution

The second method is more efficient because it completes the bubble short in one pass. In O(n) time, it changes the array to a zigzag form.

We have to keep a flag that represents the order (fewer than (<) or larger than (>) in order to conduct the bubble short. If the two elements are not in that order, switch them; otherwise, don't.

Algorithm:

1. Set the value of the flag to true.

2. From 0 to n-2, traverse the array (where n is the array's length).

  1. If the flag is true
    • Make surethe present element is larger than the one that comes after it.
    • Change the settings.
  2. Otherwise, see if the present element is larger than the one that comes after it.
    • Check to see if the current element is smaller than the next.
    • Change the settings.
  3. Toggle the flag's value.

Let's have a look at an example.

Consider the array A, which consists of three elements: [5, 3, 1]. 5 > 3 > 1 in this case. It denotes the absence of a zigzag array. Assume we're dealing with 3 and 1, which equals 3 > 1. If we switch 3 and 1, the connection becomes 5 > 1 and 1 3, and we end up with the zigzag array [5, 1, 3].

A Zigzag Array Example:

Zigzag arrays are A = [4, 2, 6, 3, 10, 1] and B = [8, 4, 6, 3, 5, 1, 10, 9]. Because there are no three consecutive array elements in either increasing or decreasing order.

The element a1 a2 a3 i.e. (2 3 6) in the array C = [5, 2, 3, 6, 1] is not a zigzag array. When the third element, 6, is removed, the array becomes [5, 2, 3, 1], a collection of a zigzag array. The following are examples of zigzag arrays:

65723
846351109
3748261

Zigzag Array in Java

Because the items (in red) do not follow the order, the following arrays aren’t zigzag at all.

2311121315171819
957821
234578962

Simple Array in Java

Convert Simple array into Zigzag Array:

Here's how to print an array in a Zigzag pattern. Assume you've been handed an array of integers and asked to sort them in a zig-zag manner. The first integer is fewer than the second integer, which is larger than the third integer, which is fewer than the fourth integer, and so on in a zig-zag pattern. As a result, the transformed array should look like this: e1 >e2 > e3 >e4 > e5 >e6.

Test cases:

Input 1:

7

4 3 7 8 6 2 1

Output 1:

3 7 4 8 2 6 1

Input 2:

4

1 4 3 2

Output 2:

1 4 2 3

Example:

import java.until.Arrays ;


Public class ZigZagArray
{
  Public static void main(String[] args)
    {
       int a[] = new int[5];
       int i, j , k;


Scanner in = new Scanner ( System.in ) ;


System.out.println( “ Enter 5 elements in array “ ) ;


       for(i = 0 ; i< 5 ; i++)
            {
 a[i] = in.nextInt() ;
             }


int[][] b = new int[5][] ;


       for ( i = 0 ; i< 5 ; i++ )
         {
                b[i] = new int[a[i]];
                for ( j = 0 ; j <a[i] ; j++ )
          {
                     b[i][j] = k;
                     k++ ;
                 }
          }


}
 }


System.out.print( “ You Create Array “ ) ;


for ( i = 0 ; i< 5 ; i++ )
 {
    for ( j = 0 ; j < b[j].length ; j++ )
      {
System.out.print( b[][]+”\t” ) ;
       }
System.out.println( ) ; 
}

Output:

Enter 5 elements in an array
1
5
2
9
4
You Create Array 1
1       2       3        4        5
1 2
1       2       3         4        5         6        7        8        9
1       2       3         4

Related Topics

How to Create Immutable Classes in Java

Introduction Java is a programming language that is entirely object-oriented, and everything in it is seen as an object. And the blueprint or template of these objects are classes. Several classes...

3 minutes read.

Balanced Parentheses in Java

One of the frequent programming issues, commonly referred to as the Balanced brackets issue, is the problem with the balanced parenthesis. Interviewers frequently provide this task, in which we must...

5 minutes read.

How to Create a Generic List in Java?

Generics are types that have parameters. The goal is to make it possible for methods, classes, and interfaces to take type (Integer, String, etc., and user-defined types) as a parameter....

4 minutes read.

Java Socket Programming

Java Socket Programming Socket programming is used for the communication between the applications, i.e., client and server running on different JRE may be connection-oriented or connectionless. The client program can be designed using the...

8 minutes read.

Java Math floor() Method

The floor() method of Math class returns the largest double value that is equal to a mathematical integer and is less than or equal to the argument. Syntax: public static double floor(double...

2 minutes read.

Cosmic Superclass in Java

The parent class of all Java classes is the Object class. The Java Object class is the parent of all Java classes, whether directly or indirectly. The Object class is...

6 minutes read.

Check the presence of Substring in a String in java

In java, the string can be treated as class and datatype. The string contains words and numbers but should be in double-quotes. Example: ” Omsairam” Substring The part of the string is called...

2 minutes read.

Insertion Sort in Java

Insertion Sort in Java Insertion sort in Java is a simple sorting algorithm that works in the same way as we hold cards in hand. Insertion sort does the sorting element-by-element,...

3 minutes read.

Java Implements Keyword

To understand about the keyword implements we need to learn about the concept of the interfaces and inheritance in java programming languages. So let us learn about the interface and...

3 minutes read.

Minimum Number of Taps to Open to Water a Garden in Java

Problem Statement The issue is that a gardener wants to water a (single-dimensional) garden using the fewest possible tap openings. The goal is to determine the minimum necessary taps to be...

8 minutes read.

Sum of digits in string in java

To find the sum of all digits in a string, you need to traverse through the string one by one character; if the character is an integer, you need to...

2 minutes read.

Java Integer doubleValue() method

The doubleValue() method of Integer class returns a double value for this Integer after a widening primitive conversion. Syntax public double doubleValue() Parameters NA Specified by This method is specified by doubleValue in class Number Return Value This...

1 minute read.

Program to find and replace characters on string in java

In JAVA, Strings are immutable. To overcome this Java String class contains a lot of methods to do operations on Strings. One such method is replace method. String Replace It returns a...

3 minutes read.

Spliterator in Java 8

In this tutorial, we will understand the meaning of spliterator in java 8. It is just like any other iterator available in java used to traverse the elements of either...

4 minutes read.

Stone Game in Java

In this tutorial, we will learn to design a stone game in Java. First of all, we will understand what is this game all about. We will grasp it through...

9 minutes read.

Java String Matches vs Contains

String Matches in Java The matches() function and its variations are used to determine whether or not a provided text matches a regular expression. The functioning as well as output of...

3 minutes read.

Alice and Bob Problem Java

Alice and Bob were two friends who liked to play games. Both together found a game, which has the description below. The game begins with an integer num, used to create...

2 minutes read.

Java Default Keyword

The Default keyword in java programming language is used as access modifier.If any of the variable or the constructor or the methods or the classes are not assigned with the...

3 minutes read.

Creation of Multi Thread in java

What are threads in Java? We can use threads to facilitate parallel processing. Threads are helpful when you wish to execute several pieces of code concurrently. A thread is a small process...

3 minutes read.

How to compare three dates in Java?

While using the date and the time in Java, we occasionally have to compare the dates. Java does not compare dates the same way it compares the two numbers. Therefore,...

6 minutes read.