-3

I'm not sure how to implement the quicksort algorithm into a nested list. If I have a list like this:

L = [['James', '1', '2'], ['Alan', '1', '1'], ['Henry', '1', '5']]

and I want to order it based on the last number in each sublist.

Output:

final = [['Henry', '1', '5'], ['James', '1', '2'], ['Alan', '1', '1']]
Billy Whales
  • 103
  • 1
  • 9

1 Answers1

0

I find an algorithm implementation from this question Quicksort with Python. And just redefine the comparison funciton:

L = [['James', '1', '2'], ['Alan', '1', '1'], ['Henry', '1', '5']]

less_than = lambda x, y: x[2] < y[2]
more_than = lambda x, y: x[2] >= y[2]

def qsort(arr):
    if len(arr) <= 1:
        return arr
    else:
        return qsort([x for x in arr[1:] if less_than(x, arr[0])]) + [arr[0]] + qsort([x for x in arr[1:] if more_than(x, arr[0])])


print(qsort(L))

Output:

[['Alan', '1', '1'], ['James', '1', '2'], ['Henry', '1', '5']]

Hope this helps.

Community
  • 1
  • 1
McGrady
  • 10,869
  • 13
  • 47
  • 69