def InsSort(myList):
UBound = len(myList)
for i in range(1,UBound):
NextItem = myList[i]
position = i - 1
while position>=0 and myList[position]>NextItem:
myList[position+1] = myList[position]
position = position - 1
myList[position+1] = NextItem
UnsortList = []
n = int(input("Enter number of elements in the List:\n"))
for j in range(0,n):
element = int(input("Input element:\n"))
UnsortList.append(element)
print(UnsortList)
myList = UnsortList
InsSort(myList)
print(str(UnsortList)+" is now sorted --> "+str(myList))
I let the user create their own array "UnsortList" using their input, I then copy it to "myList", and call the funtion InSort(myList) to sort the "myList" array, but when it excecutes print(str(UnsortList)+" is now sorted --> "+str(myList))
, str(UnsortList)
shows up as the sorted "myList" as well
An example output:
First it outputs the unsorted array via print(UnsortList)
[-9, 3, 6, 1, -3, 55, 22, -18]
Then where it is supposed to print the Unsorted and sorted array via print(str(UnsortList)+" is now sorted --> "+str(myList))
, this is what it outputs:
[-18, -9, -3, 1, 3, 6, 22, 55] is now sorted --> [-18, -9, -3, 1, 3, 6, 22, 55]
The output I want is:
[-9, 3, 6, 1, -3, 55, 22, -18] is now sorted --> [-18, -9, -3, 1, 3, 6, 22, 55]
What could be the solution to this?
Thanks to OldBill, I realised myList = UnsortList
does not create a copy of the list as I intended, the correct syntax is supposed to be myList = UnsortList.copy()
Copyright Notice:Content Author:「EmergencyEgg」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/74130382/made-a-code-for-insertion-sort-declared-a-sorted-and-an-unsorted-array-but-the