I am going through Elements of Programming Interviews in Python and am confused by this problem. The problem takes an array of numbers and is supposed to output a list where the even numbers are ordered first. You're supposed to do it without allocating extra storage.
They gave a solution, and I tested it out, but it didn't give the right answer.
def even_odd(arr):
    next_even = 0
    next_odd = len(arr) - 1
    while next_even < next_odd:
        if arr[next_even] % 2 == 0:
            next_even += 1
            print("next" + str(next_even))
        else:
            arr[next_even] = arr[next_odd]
            arr[next_odd] = arr[next_even]
            next_odd -= 1
            print(arr)
            print("first" + str(arr[next_even]))
    return arr
print(even_odd([1, 2, 3, 4, 5, 6]))
The result was [6, 2, 4, 4, 5, 6] I also don't understand the mechanism of swapping elements with each other (A[next_even], A[next_odd] = A[next_odd], A[next_even]). I think this is an important concept when you can't create another array, you have to swap elements, but I just can't seem to wrap my head around it.
Can someone help where my code went wrong and explain the swapping? Thanks!
 
     
     
     
     
     
    