Convert an Array into Zig-Zag Fashion
💻 coding

Convert an Array into Zig-Zag Fashion

1 min read 272 words
1 min read
ShareWhatsAppPost on X
  • 1The zig-zag rearrangement requires the array to follow the pattern a < b > c < d > e < f.
  • 2The initial solution sorts the array, achieving a time complexity of O(n log n).
  • 3An optimized approach rearranges the array in O(n) time by swapping elements based on their order.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The zig-zag rearrangement requires the array to follow the pattern a < b > c < d > e < f."

Convert an Array into Zig-Zag Fashion

You are given an array of some distinct elements, you have to rearrange those elements of the array in a zig-zag fashion. The resultant array should be in format a < b > c < d > e < f.

First, we will solve this problem in nlogn Time complexity. in this scenario, we will first sort the Array and then will apply the zig-zap logic.

import java.util.Arrays;

public class ZigZagArray {
	public static void main(String[] args) {
		
		//nlong approach
		int[] arr = new int[] {4, 3, 7, 8, 6, 2, 1};
		
		//Sort the array 
		Arrays.sort(arr);
		
		//Swap elements in pair skipping first element
		for(int i=1;i<arr.length-1;i+=2) {
			int temp = arr[i];
			arr[i]=arr[i+1];
			arr[i+1]=temp;
		}
		
		StringBuilder str = new StringBuilder();
		for(int i=0;i<arr.length;i++) {
			str.append(arr[i]).append(' ');
		}
		System.out.print(str);
	}
}

The time complexity of the above solution is O(nlogn) for sorting the array using quick sort.

Now We will Optimize our solution for O(n) time complexity.

import java.util.Arrays;

public class ZigZagArray {
	public static void main(String[] args) {
		
		//O(n) approach
		int[] arr = new int[] {4, 3, 7, 8, 6, 2, 1};
		
		//flag to keep track of swapping order, i.e either increasing or decrasing order logic
		Boolean isGreaterOrder = true;
		
		//Swap elements in in alternate order
		for(int i=0;i<arr.length-1;i++) {
			//if it is increasing order
			if(isGreaterOrder) {
				if(arr[i]<arr[i+1]) {
					int temp = arr[i];
					arr[i]=arr[i+1];
					arr[i+1]=temp;
				}
				isGreaterOrder = !isGreaterOrder;
			}
			else {
				if(arr[i]>arr[i+1]) {
					int temp=arr[i];
					arr[i]=arr[i+1];
					arr[i+1]=temp;
				}
				isGreaterOrder = !isGreaterOrder;
			}
		}
		
		StringBuilder str = new StringBuilder();
		for(int i=0;i<arr.length;i++) {
			str.append(arr[i]).append(' ');
		}
		System.out.print(str);
	}
}

The Time complexity of the above solution is O(n) as we are iterating through the Array only once.

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

AskGif

Published on 13 July 2018 · 1 min read · 272 words

Part of AskGif Blog · coding

You might also like