Home > front end >  How do i sort a 2D array or multiple arrays by the length of the array using bubble sort
How do i sort a 2D array or multiple arrays by the length of the array using bubble sort

Time:10-05

trying to write a Python function: def compare_lengths(x, y, z)

which takes as arguments three arrays and checks their lengths and returns them as a triple in order of length.

For example, if the function takes [1,2,3], [10,20,30,40] and [65,32,7] as input, want it to return either ([1,2,3], [65,32,7], [10,20,30,40]) or ([65,32,7], [1,2,3], [10,20,30,40])

it can take it as either:

Array = [1,2,3],[10,20,30,40],[65,32,7]

or:

x = [1,2,3]
y = [10,20,30,40]
z = [65,32,7]

but it needs to be sorted as either:

([1,2,3], [65,32,7], [10,20,30,40])

or:

([65,32,7], [1,2,3], [10,20,30,40])

using bubble sort

CodePudding user response:

You can do this, the only difference being the condition used is the length of the array instead of an individual value.

n = len(arr)
for i in range(n):
    for j in range(n-i-1):
        if len(arr[j]) > len(arr[j 1]):
            arr[j], arr[j 1] = arr[j 1], arr[j]

  • Related