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) which takes as arguments three arrays and checks their lengths and returns them as a triple in order of length. For
Solution 1:
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]
Solution 2:
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:
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:
arrays = [[1, 2, 3], [10, 20, 30, 40], [65, 32, 7], [3, 3]]
result = sorted(arrays, key=len)
print(result)
Post a Comment for "How Do I Sort A 2D Array Or Multiple Arrays By The Length Of The Array Using Bubble Sort"