-1
def merge_sort(alist):
##    print("The list entering the function is ",alist)


    if (len(alist)>1): 

        mid=len(alist)//2
        left_list=alist[0:mid]
        right_list=alist[mid:]


        merge_sort(left_list)
        merge_sort(right_list)

##        print("alist is ",alist)


        i=0
        j=0
        k=0


        while i < len(left_list) and j < len(right_list):
            if left_list[i]<right_list[j]:
                alist[k]=left_list[i]
                i+=1
            else:
                alist[k]=right_list[j]
                j+=1
            k+=1

        while i < len(left_list):
            alist[k]=left_list[i]
            i+=1
            k+=1

        while j< len(right_list):
            alist[k]=right_list[j]
            j+=1
            k+=1

        #return(alist)


unsortedlist=[56,2,3,91,45,34,56,2,4,7,8,1,3]
merge_sort(unsortedlist)

print(unsortedlist)

The output is [1, 2, 2, 3, 3, 4, 7, 8, 34, 45, 56, 56, 91]

Why the unsortedlist list changed even though nothing was returned ?

roganjosh
  • 12,594
  • 4
  • 29
  • 46

1 Answers1

0

The list is being mutated within the function as a 'side-effect' of the functions actions. When you pass 'alist' into your function mergesort, you pass in a reference (i.e. the location in memory) of alist. Within mergesort you change the value at that memory location (e.g. alist[0] = 1 changes the value in memory located at alist[0] to 1). Now when the mergesort function terminates even though it doesn't return anything, you have still altered the values found in alist. Hence when you later reference that memory location again, you find that it's value has changed even outside of the mergesort function.

  • Just to clarify, when I say you pass in a reference to alist what really happens is that when you call your function mergesort(alist) the variable alist creates a new reference which points to the same place in memory as the outer alist object. [Read more here](http://stackoverflow.com/questions/986006/how-do-i-pass-a-variable-by-reference) – Anthony Alridge Mar 28 '17 at 21:52