For an assignment where we have to reverse bubble sort. After each movement of this sort we must store the array into a different array known as. The problem being is that the with each movement in Array A it automatically changes the array in the other array. IE giving an output like this
[[1, 3, 4, 6, 7, 8, 9, 10], [1, 3, 4, 6, 7, 8, 9, 10], [1, 3, 4, 6, 7, 8, 9, 10], [1, 3, 4, 6, 7, 8, 9, 10]]
When it should be doing an output like this:
[[1, 3, 4, 6, 10, 7, 9, 8], [1, 3, 4, 6, 7, 10, 8, 9], [1, 3, 4, 6, 7, 8, 10, 9][1, 3, 4, 6, 7, 8, 9, 10]]
Full code:
def alt_bubblesort(A: list, size: int) -> list:
#Final array of arrays, stores each movement of the bubble sort
masterList = []
#placeholder variable
holder = min(A)
#puts the starting element at the start of the array
A.remove(min(A))
A.insert(0,holder)
#Traverses the array
for i in range(size):
print(A)
masterList.append(A)
for j in reversed(range(1,size)):
if A[j] < A[j-1]:
A[j], A[j-1] = A[j-1], A[j]
I did not check whether the sorting algorithm is implemented correctly. But if I get your problem right, you can use copy.deepcopy:
import copy
...
for i in range(size):
print(A)
masterList.append(copy.deepcopy(A)) # This line has changed
for j in reversed(range(1,size)):
if A[j] < A[j-1]:
A[j], A[j-1] = A[j-1], A[j]