user20807261
user20807261

Reputation:

Why is my python merge sort algorithm not working?

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.

Upvotes: 0

Views: 45

Answers (1)

Vuzz
Vuzz

Reputation: 56

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)

Upvotes: 1

Related Questions