PM25
PM25

Reputation: 35

Same print statement provides different output for sorting algorithm (Insertion Sort)

I have coded up the algorithm for insertion sort and have ensured that it works; however, depending on how I print the sorted list, the output is different. For example,

x = some_unsorted_list
x = insertionSort(x)
print(x)

will print the sorted list just fine. On the other hand,

x = some_unsorted_list
insertionSort(x)
print(x)

will print some partially sorted-unsorted list. Here is my code for selection sort:

def insertionSort(L):
    endList = len(L) - 1 

    for i in range(1,endList+1,1): 
        insertVal = L[i]  
        j = i - 1 

        while j >= 0 and L[j] > insertVal:
            L[j+1] = L[j]    
            j -= 1          
        L[j+1] = insertVal  
    #print(L)
    return L

Note that the print statement commented out always provides the sorted list, which is causing my confusion.

Edit (Important information I left out): Here's how I'm calling the insertion sort. Let v1, v2, and v3 be unsorted lists.

for i in [v1,v2,v3]:
    x = list(i)
    insertionSort(x)
    print(x) 

And recall, this is where errors arise. However the following code does not produce errors:

print(insertionSort(v1))
print(insertionSort(v2))
print(insertionSort(v3))

Upvotes: 0

Views: 90

Answers (1)

Moosa Saadat
Moosa Saadat

Reputation: 1167

When you pass a variable to a function, a new copy is made. So, when you are passing x to your function, a new variable L will be made which will have the same value as x.

Now, we have 2 different variables named x and L.

In your function, you are making changes to L and outside the function, you are printing x. Therefore, you are getting wrong results. Because L was sorted NOT x.

The difference among codes

In your first code snippet x = insertionSort(x), overrides the value of x with the value returned by function (which will be a sorted list always). So, it prints the right result. In your second code snippet, you are NOT overriding the value of x. Therefore, you are getting wrong results.

Upvotes: 2

Related Questions