简体   繁体   English

我如何使用冒泡排序按数组的长度对二维数组或多个 arrays 进行排序

[英]How do i sort a 2D array or multiple arrays by the length of the array using bubble sort

trying to write a Python function: def compare_lengths(x, y, z)试图写一个 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.它以 arguments 为三个 arrays 并检查它们的长度并按长度顺序将它们作为三元组返回。

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])例如,如果 function 将 [1,2,3]、[10,20,30,40] 和 [65,32,7] 作为输入,希望它返回 ([1,2,3], [ 65,32,7], [10,20,30,40]) 或 ([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使用冒泡排序

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]

You needn't invent your own sorting algorithm or use bubble sort.您无需发明自己的排序算法或使用冒泡排序。 It can be done with Python's built-in sorting mechanism and specifying the sorting criteria as a lambda:可以使用 Python 的内置排序机制并将排序标准指定为 lambda 来完成:

arrays = [[1, 2, 3], [10, 20, 30, 40], [65, 32, 7], [3, 3]]
result = sorted(arrays, key=lambda arr: len(arr))
print(result)

Or as an inplace sort:或者作为就地排序:

arrays = [[1, 2, 3], [10, 20, 30, 40], [65, 32, 7], [3, 3]]
arrays.sort(key=lambda arr: len(arr))
print(arrays)

If you understand the concept of function pointers, you may even do it shorter:如果你理解 function 指针的概念,你甚至可以做得更短:

arrays = [[1, 2, 3], [10, 20, 30, 40], [65, 32, 7], [3, 3]]
result = sorted(arrays, key=len)
print(result)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM