Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

I am trying to reverse an array.

For example, if I have:

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

I want to have an output like this:

     output = [6,1,5,2,4,3]

What I am doing is that I want the largest number, followed by the smallest number, followed by the second largest number, followed by the second smallest number, etc.

I have the code but doesn't work for all cases.

Here is a copy of my code

def meanderingArray(arr) : 

    n = len(arr)

    arr.sort() 

  

    tempArr = [0] * (n + 1) 

  

    ArrIndex = 0

    i = 0

    j = n-1

      

    while(i <= n // 2 or j > n // 2 ) : 

      

        tempArr[ArrIndex] = arr[j] 

        ArrIndex = ArrIndex + 1

        tempArr[ArrIndex] = arr[i] 

        ArrIndex = ArrIndex + 1

        i = i + 1

        j = j - 1

    for i in range(0, n) : 

        arr[i] = tempArr[i] 

    return arr

      

meanderingArray([22231,44423,66574,-14122,-12322,14476])

IndexError                                Traceback (most recent call last)

<ipython-input-28-8993ecc448e2> in <module>

----> 1 meanderingArray([22231,44423,66574,-14122,-12323,14476])

<ipython-input-26-24690fd05e2d> in meanderingArray(arr)

     14         tempArr[ArrIndex] = arr[j]

     15         ArrIndex = ArrIndex + 1

---> 16         tempArr[ArrIndex] = arr[i-1]

     17         ArrIndex = ArrIndex + 1

1 Answer

0 votes
by (36.8k points)

Your code doesn't run when the array has an odd length. You will be taking the middle element twice, once using I and once using j, and then appending it twice. It would have stayed more clear what was broken if instead, you wrote:

tempArray = []

while.....

    tempArray.append(arr[j])

    tempArray.append(arr[i])

    ...

first, get an AIOOB exception, you would see that the middle element was added twice. You need to cancel out of the early if i==j

If you are a beginner and want to know more about Data Science the do check out the Data Science course

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...