Home > other >  I have to provide the argument arr twice, once in Sorting(arr) and again in quicksort(arr), How can
I have to provide the argument arr twice, once in Sorting(arr) and again in quicksort(arr), How can

Time:09-17

class Sorting:
    def __init__(self, arr):
        self.arr = arr
        n = len(arr)

    def quicksort(self,arr):
        if len(arr) <= 1:
            return arr

        else:
            pivot = arr[0]
            del arr[0]

            items_greater = []
            items_lower = []
            for item in arr:
                if item > pivot:
                    items_greater.append(item)
                else:
                    items_lower.append(item)

            return sor.quicksort(items_lower)   [pivot]   sor.quicksort(items_greater)




arr = [4,3,2,1,-5,-89,10]
n = len(arr)
sor = Sorting(arr)
print(sor.quicksort(arr))

Output: [-89, -5, 1, 2, 3, 4, 10]

I have to provide the argument arr twice, once in Sorting(arr) and again in quicksort(arr), How can I rewrite the code using arr only once ?

CodePudding user response:

Make arr an optional argument, and use self.arr when it's not provided. You only need to pass it explicitly in the recursive calls.

class Sorting:
    def __init__(self, arr):
        self.arr = arr
        n = len(arr)

    def quicksort(self, arr = None):
        if arr is None:
            arr = self.arr

        if len(arr) <= 1:
            return arr

        else:
            pivot = arr[0]
            del arr[0]

            items_greater = []
            items_lower = []
            for item in arr:
                if item > pivot:
                    items_greater.append(item)
                else:
                    items_lower.append(item)

            return sor.quicksort(items_lower)   [pivot]   sor.quicksort(items_greater)

CodePudding user response:

Just remove the __init__() method:

class Sorting:
    def quicksort(self,arr):
        if len(arr) <= 1:
            return arr

        else:
            pivot = arr[0]
            del arr[0]

            items_greater = []
            items_lower = []
            for item in arr:
                if item > pivot:
                    items_greater.append(item)
                else:
                    items_lower.append(item)

            return sor.quicksort(items_lower)   [pivot]   sor.quicksort(items_greater)

arr = [4,3,2,1,-5,-89,10]

sor = Sorting()
print(sor.quicksort(arr))

Same output as before.

  • Related