1

I've no questions about how an array are sorted. I'm asking how a randomly selected array I sent to the sort function is automatically sorted, even though I've assigned the output to a different array.

bubbleList = createRandomArray()
sortedList = BubbleSort(bubbleList)
print(bubbleList)
print(sortedList)

A sample output of the piece of code written as above is as follows:

[-15, -14, -12, -12, -9, -6, -5, -4, 0, 10]
[-15, -14, -12, -12, -9, -6, -5, -4, 0, 10]

But if I print the unsorted list without sending it to the function, there's no sorting. Then the output is as follows:

[-14, -6, -15, 0, -5, -9, -4, -12, -12, 10]
[-15, -14, -12, -12, -9, -6, -5, -4, 0, 10]

Could it be due to the automatic assignment made by the python? Many thanks.

Added BubbleSort:

def BubbleSort(inlist):
n = len(inlist)
for i in range(n-1, -1, -1):
    for j in range(0, i):
        if not(inlist[j] < inlist[j+1]):
            inlist[j], inlist[j+1] = inlist[j+1], inlist[j]
return inlist

2 Answers2

2

It appears the implementation of the BubbleSort method you are using is sorting the array in place. That is, it is modifying the the memory assigned to that list object. Not all python sorting methods work this way. sorted(list) for instance will not modify the passed list.

David Stein
  • 379
  • 2
  • 15
2

What David said is correct. Just to elaborate:

When you pass an argument to an object, like a list, to a python function, it passes by reference, which means the variable inside the function references the same data as the variable outside. Therefore, if you modify the variable inside the function then it will also modify the variable outside the function.

The reason this exists is that if you have very long lists, then it takes a long time to make a copy. Many languages copy by default (C++ comes to mind) and allows passing by reference through a special operator, but Python just does this automatically.

There are many ways to copy a list in Python3, but the most pythonic is probably new_list = old_list.copy(). See this answer for other options :)

bubbleList = createRandomArray()
sortedList = BubbleSort(bubbleList.copy())
print(bubbleList)
print(sortedList)
Exr0n
  • 358
  • 1
  • 9