Convert Arrar into Zig Zag

In this class, We discuss Convert Array into Zig Zag

The reader can take the complete competitive coding course. Click Here.

Question:

Given N distinct array elements.

The task is to rearrange the elements in a zig-zag fashion so that the converted array should be in the below form.

arr[0] < arr[1] > arr[2] < arr[3] > . . . .

Example:

arr[] = [4, 3, 7, 8, 2, 6, 1]

Output: [3, 7, 4, 8, 2, 6, 1]

Time complexity = O(N)

Space complexity = O(1)

Logic:

[4, 3, 7, 8, 2, 6, 1]

Condition:

even position element condition = arr[i] < arr[i+1]

odd position element condition = arr[i] > arr[i+1]

Code:

class Solution:

    def zigZag(self, arr, n):

        flag = 1

        for i in range(n-1):  

            if flag == 1: 

                if arr[i] > arr[i+1]:

                    arr[i], arr[i+1] = arr[i+1], arr[i]

            else: 

                if arr[i] < arr[i+1]:

                    arr[i], arr[i+1] = arr[i+1], arr[i]

            flag = (1 – flag)

        print(arr)

n = int(input())

arr=list(map(int,input().strip().split()))

ob = Solution()

ob.zigZag(arr,n)

print(arr)