×

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

Hidden classes in Java

There specifically are some APIs available in the market that generally is harmful to be used in our programs specifically literally, and until JDK 15, there, for all intents and...

4 minutes read.

Hashtable in Java

Hashtable in Java The Hashtable class implements the Map interface and extends the Dictionary class. It implements a hash table which shows the key-value relation, i.e., it maps the keys to the values....

9 minutes read.

Narcissistic Number in Java

A Narcissistic number is made up of digits that have been added together and raised to powers equal to the number of digits in the original number. In those other...

3 minutes read.

Set Up the Environment in Java

The Java is regarded as the pure object-oriented programming language. The Java applications are first compiled into the byte-code and then run by using the JVM. The Java is the...

4 minutes read.

Arithmetic Operations on String in Java

Introduction Arithmetic, Relational, Bitwise, and Logical operators are all available in Java. Simple mathematical calculations are performed using Java arithmetic operators. Basic Arithmetic operators are considered in Java to be Addition,...

4 minutes read.

Java Hello World

Let’s start by writing a simple program that prints “Hello World” to the output window. Write the program into any text editor or IDE (Eclipse, Netbeans, etc.) and save the file with the...

2 minutes read.

Java Base64 Encoding and Decoding

Introduction to Encoding and Decoding Encoding is the process of putting the sequence of characters like letters, numbers, punctuations, and other symbols into a specialised format for the efficient transmission or...

11 minutes read.

Empty Statement in Java

The three sorts of statements in Java are control, expression, and declaration statements. Additionally, another statement is referred to as an empty statement. In this section, we will discuss about...

4 minutes read.

How to add 6 Months to the Current Date in Java?

In this tutorial, we will learn how to add 6 months to the local or current date in Java language. We will begin our topic with basic concepts and would...

3 minutes read.

Constructor in Java with Example

Java Constructor  The constructor is used for object initialization. It's a block of code that initializes a newly created object. It contains a collection of statements that are executed at the...

5 minutes read.

Differences between Lock and Monitor in Java Concurrency

In this tutorial, we will discuss the overview of Lock and Monitor and the differences between them. Introduction Java Concurrency is the ability to perform specific tasks at a time parallelly. The...

4 minutes read.

Difference Between Java and PHP

The two most used programming languages are PHP and Java. Both of them have a lot of similarities and distinctions. Let's first grasp each of them individually before examining their...

3 minutes read.

Convert JSON File to String in Java

Before understanding the conversion of JSON file to string, one must know about JSON. What is JSON? JSON stands for JavaScript Object Notation. It is an open standard format lightweight, text-based, and...

3 minutes read.

Least Operator to Express Number in Java

In this article, we will learn about how to obtain a target number using a single number or a single integer by leveraging least operators in Java. There can be...

3 minutes read.

Java import packages

To know about the importing the packages of Java, we need to understand about how to packages work. Packages The package in Java is a collection of Classes and Interfaces. The packages...

3 minutes read.

Reverse a String in Java

Reversing a string means that if we have a string called “what is your name”, the reversed format is “eman ruoy si tahw”. Reversing a string involves totally flipping the...

3 minutes read.

Blockchain in Java

Blockchain is a continuously expanding ledger that maintains an immutable, secure, and chronological record of all transactions that have ever occurred. It can be utilized to securely transfer money, assets,...

9 minutes read.

Java Localization

Internationalization is the process of creating a software application that can be translated into different languages and regions without modifying the application. Creating a locale-specific application raises the cost of...

3 minutes read.

Differences between Byte Code and Machine Code

This tutorial will discuss the differences between Byte Code and Machine Code. Before that, let's try to know what byte and machine code is. Introduction Every computer has a set of instructions...

4 minutes read.

Second Smallest Number in an Array in Java

By sorting the arrays and returning the second element, we can use Java to discover the second-smallest number in the array. Input:  arr[] = {10, 11, 13, 15, 34, 51} Output: The...

6 minutes read.