prony
prony

Reputation: 75

Why does input array change inside the recursive function?

I am trying to understand quick search algorithm in pyhton. Here is the code I am working on:

def partition2(a, l, r):
x = a[l]
j = l;
for i in range(l + 1, r + 1):
    if a[i] <= x:
        j += 1
        a[i], a[j] = a[j], a[i]
a[l], a[j] = a[j], a[l]
return j



def randomized_quick_sort(a, l, r):

if l >= r:
    return
k = random.randint(l, r)
a[l], a[k] = a[k], a[l]
#use partition3
m = partition2(a, l, r)


randomized_quick_sort(a, l, m - 1);
randomized_quick_sort(a, m + 1, r);

Then I am calling this function defining a variable. For example:

b = [5,1,4]
randomized_quick_sort(b, 0, 2)

MY question is that when I try to print b after the function call, it prints as [1,4,5]. So, how come the value of this array is changing within the function??? It is not a global variable. Whey the local variables inside the function overrides it?? Please help

Upvotes: 3

Views: 1326

Answers (1)

AJ_
AJ_

Reputation: 1485

When you provide a list as a function argument you are passing a pointer to that list, meaning the parameter a isn't its own array, but a pointer to b.

What you are looking to do is provide only the items of the array b to randomized_quick_sort()

This can be done by making the following adjustment:

randomized_quick_sort (b[:], 0, 2);

Notice b[:] instead of b. Now, when you print b after calling the function you will have the same values as you did before.

You can find more information about this here

Upvotes: 2

Related Questions