Home > Mobile >  Why isn't array element changing position?
Why isn't array element changing position?

Time:09-16

I have an array of numbers to be sorted in ascending order.

def sort(array):

    n = len(array)
    for outer_iteration in range(1, n):
        for inner_iteration in range(1, n):
            number1 = array[inner_iteration - 1]
            number2 = array[inner_iteration]
            if number1 > number2:
                array[inner_iteration - 1] , array[inner_iteration] = array[inner_iteration] , array[inner_iteration - 1]


array = [10,47,1,0,-39,-5]
sort(array)
print(array)

This works perfectly fine. But when I change the tuple that swaps the element positions, the array is no longer sorted.

def sort(array):

    n = len(array)
    for outer_iteration in range(1, n):
        for inner_iteration in range(1, n):
            number1 = array[inner_iteration - 1]
            number2 = array[inner_iteration]
            if number1 > number2:
                number1 , number2 = number2, number1

array = [10,47,1,0,-39,-5]
sort(array)
print(array)

I checked on PythonTutor and it seems to me that in the 2nd block of code, the numbers assigned to number1 and number 2 really do swap around, but only in the variables, not in the array. I used tuples in both cases to swap and since number1 and number2 were assigned to array[inner_iteration - 1] and array[inner_iteration], why does the second case behave differently from the first?

CodePudding user response:

So in the second code snippet, you are just changing the variables number1 and number2 to some new value (in your case you are just swapping the values). But those values are not references to the numbers in the array at those positions, which means the change doesn't get reflected in the array. To update the values in the array, you need to re-assign the numbers back to the array after the variables are changed.

def sort(array):

    n = len(array)
    for outer_iteration in range(1, n):
        for inner_iteration in range(1, n):
            number1 = array[inner_iteration - 1]
            number2 = array[inner_iteration]
            if number1 > number2:
                number1 , number2 = number2, number1
            array[inner_iteration - 1] = number1
            array[inner_iteration] = number2

array = [10,47,1,0,-39,-5]
sort(array)
print(array)

The above corrected code will help you understand the reasoning.

CodePudding user response:

Take a look at a simple example:

a = 5
b = a
b = 3
print(a) # prints 5

In this case, b = a does not mean b is always equal to a. If you reassign b to a new value sooner, a keeps its first value.

  • Related