Write a program to declare a single-dimensional array of size N, where N is an integer greater than 2 and less than 10. Allow the user to input positive integers into this array. Display an appropriate error message for an invalid input.
Rearrange the array in zig-zag order in the form arr0 ≤ arr1 ≥ arr2 ≤ arr3 ≥ arr4 … using in-place swaps only.
Example:
INPUT: [4, 3, 7, 8, 6, 2, 1]
OUTPUT: [3, 7, 4, 8, 2, 6, 1] after rearranging in zig-zag order.
Perform the following tasks on the array:
a) Display original array.
b) Transform to zig-zag order.
c) Display transformed array.
Test your program with the following data and some random data:
Example 1
INPUT:
N = 5
Array Elements: 20, 5, 25, 30, 18
OUTPUT:
Original Array: 20, 5, 25, 30, 18
Zig-Zag Array: 5, 25, 20, 30, 18
Example 2
INPUT:
N = 8
Array Elements: 100, 50, 175, 25, 12, 150, 17, 200
OUTPUT:
Original Array: 100, 50, 175, 25, 12, 150, 17, 200
Zig-Zag Array: 50, 175, 100, 150, 12, 25, 17, 200
Example 3
INPUT:
N = 6
Array Elements: 21, 4, 34, -2, 9, 10
OUTPUT: INVALID INPUT
Example 4
INPUT:
N = 2
OUTPUT: INVALID INPUT
import java.util.Scanner;
class ZigZag{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.print("N = ");
int n = in.nextInt();
if(n < 3 || n > 9){
System.out.println("INVALID INPUT");
return;
}
int a[] = new int[n];
System.out.println("Array Elements:");
for(int i = 0; i < a.length; i++){
a[i] = in.nextInt();
if(a[i] < 0){
System.out.println("INVALID INPUT");
return;
}
}
System.out.print("Original array: ");
for(int i = 0; i < a.length; i++)
System.out.print(a[i] + " ");
//zig-zag arrangement
boolean status = true;
for(int i = 0; i < a.length - 1; i++){
if(status){
if(a[i] > a[i + 1])
swap(a, i, i + 1);
}
else{
if(a[i] < a[i + 1])
swap(a, i, i + 1);
}
status = !status;
}
System.out.print("\nZig-zag array: ");
for(int i = 0; i < a.length; i++)
System.out.print(a[i] + " ");
System.out.println();
}
public static void swap(int a[], int i, int j){
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}