0

I want to sort a list of instances (ClientInfo - class) by their name using merge sort algorithm.
I've tried to built the algorithm in Python but when I run it, I have this error: error How can I solve it?


def mergesort(lst, *, key=lambda x: x, reverse=False):
    """
    MergeSort implementation
    :param lst: the list that will be sorted
    :param key: the function by witch it is sorted
    :param reverse: True - ascending sort, False - descending sort
    :return: return the sorted list
    """
    if len(lst) > 1:
        pivot = len(lst) // 2
        left_half = lst[:pivot]
        right_half = lst[pivot:]

        mergesort(left_half)
        mergesort(right_half)

        i = 0
        j = 0
        k = 0
        while i < len(left_half) and j < len(right_half):
            if reverse is False:  # ascending sort
                if key(left_half[i]) < key(right_half[j]):
                    lst[k] = left_half[i]
                    i += 1
                else:
                    lst[k] = right_half[j]
                    j += 1
                k += 1
            elif reverse is True:  # descending sort
                if key(left_half[i]) < key(right_half[j]):
                    lst[k] = right_half[j]
                    j += 1
                else:
                    lst[k] = left_half[i]
                    i += 1
                k += 1

Here I call the function
BTW: If I write the function like this, it works, but I want it to be generic.

1
  • 1
    Show errors and other textual information as properly formatted text in the question, not as comment, image or external link. Commented Dec 18, 2022 at 11:12

1 Answer 1

1

I've tried to built the algorithm in Python but when I run it, I have this error: error How can I solve it?

You need to overload the < operator, here's an example:

class ClientInfo:

    name = None

    def __init__(self, name):

        self.name = name

    # overloading of operator <
    def __lt__(self, c):

        return self.name < c.name

    # overloading of print
    def __str__(self):

        return "Name: {}".format(self.name)


v = [ClientInfo("c"), ClientInfo("z"), ClientInfo("a")]

for c in sorted(v):
    print(c)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.