Rearrange Array Elements Efficient Code

In this class, We discuss Rearrange Array Elements Efficient Code.

For Complete YouTube Video: Click Here

The reader should have basic programming skills. Click Here to learn basic coding.

Take a list of elements in ascending order.

Place the elements in the following order.

Maximum element, Minimum element, second maximum element, second minimum element, and so on.

Example:

a = [1,2,3,4,5,6,7]

Rearrange elements = [7,1,6,2, 5,3,4]

Time Complexity: O(n)

Space complexity: O(1)

Watch our youtube video for coding intuition.

Code:

def rearrange(arr, n): 

        maxindex=n-1

        minindex= 0

        maxelement=arr[n-1]+1

        for i in range(n):

            if((i%2)==0):

               arr[i]+=(arr[maxindex]%maxelement)*maxelement

               maxindex-=1

            else:

               arr[i]+=(arr[minindex]%maxelement)*maxelement

               minindex+=1

        for i in range(n):

            arr[i]=arr[i]//maxelement

n = int(input(“enter n value”))

arr=[]

for i in range(n):

    x=int(input())

    arr.append(x)

rearrange(arr,n)

print(arr)