Neil Kumar
Neil Kumar

Reputation: 13

Order multiple sorted arrays

This is an interesting problem:

I have sorted arrays

a1 : [50,30,20,5]
a2 : [30,10,3,1]
a3 : [50,40,30,10]

Each array is sorted, I need to arrange the array in order of which array has the highest number, if there's a tie consider next element in array.

Ex. In above example 50 is tie between a1 and a3 so we compare 30 and 40 hence the order is

a3,a1,a2

How to do this in python? What should be the algorithm to achieve this.

Upvotes: 0

Views: 87

Answers (1)

Kevin
Kevin

Reputation: 76194

Comparing two lists in Python compares elements like that by default, so all you have to do is put your lists in a list and sort it.

my_arrays = [
    [50,30,20,5],
    [30,10,3,1],
    [50,40,30,10]
]

my_arrays.sort(reverse=True)

print my_arrays

Result:

[
    [50, 40, 30, 10], 
    [50, 30, 20, 5], 
    [30, 10, 3, 1]
]

Upvotes: 16

Related Questions