Home > Software design >  Made a code for insertion sort, declared a sorted and an unsorted array, but the unsorted array is o
Made a code for insertion sort, declared a sorted and an unsorted array, but the unsorted array is o

Time:10-20

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()

CodePudding user response:

The assignment myList = UnsortList is meaningless as they myList will just be a reference to UnSortList

Your implementation of the insertion sort is flawed.

Using hard-coded values:

def insertionSort(array):
    for step in range(1, len(array)):
        key = array[step]
        j = step - 1       
        while j >= 0 and key < array[j]:
            array[j   1] = array[j]
            j -= 1
        array[j   1] = key

myList = [-18, -9, -3, 1, 3, 6, 22, 55]
insertionSort(myList)
print(myList)

Output:

[-18, -9, -3, 1, 3, 6, 22, 55]
  • Related