3
votes

I have written the code for quick sort in python, but this code is throwing an error.

----------


    k=0
    def partition(arr,low_index,high_index):
        key = arr[low_index]
        i = low_index + 1;
        j = high_index

        while True:
            while (i<high_index and key>=arr[i]):
                i+=1
            while (key<arr[j]):
                j-=1
            if i<j:
                arr[i,j] = arr[j,i]
            else:
                arr[low_index,j]=arr[j,low_index]
                return j

    def quicksort(arr,low_index,high_index):
         if low_index < high_index:
            j = partition(low_index,high_index,arr)
            print("Pivot element with index "+str(j)+" has thread "+str(k))
            if left<j:
                k=k+1
                quicksort(arr,low_index, j - 1)
            if i<right:
                k=k+1
                quicksort(arr,j+1,high_index)
         return arr

    n = input("Enter the value n ")
    arr=input("Enter the "+str(n)+" no. of elements ")
    brr=quicksort(arr,0,n-1)
    print("Elements after sorting are "+str(brr))

----------

The error it is throwing is

Enter the value n 4

Enter the 4 no. of elements [5,6,2,7] Traceback (most recent call last): File "C:\Users\devendrabhat\Documents\dev\dev\quick.py", line 38, in brr=quicksort(arr,0,n-1) TypeError: unsupported operand type(s) for -: 'str' and 'int'

3
can u explain please - Devendra Bhat
Python receives input as a string. You need to use the function int() on that input to turn it into an integer and catch possible exceptions. - MKesper

3 Answers

1
votes

n is string. So you need to change it to int:

n = int(n)

If you input [5,6,2,7] on line 37, python interpret it as string like "[5,6,2,7]". So, you need to convert string to list.

arr = eval(arr)
2
votes

You need to change n to an integer, not a string. Your error is telling you, that you are trying to perform an operation (- in this case) on a string and an integer. Change str(n) to int(n) so you have the same type throughout.

1
votes

you are declaring 'n' as string there in your code. And trying to perform arithmetic operation with string.

So it is giving that error. Change this str(n) to int(n).

It will work !!!