sort 2d array python code example

Example 1: sort by index 2d array python

a = [[9, 9, 2], [9, 9, 3], [9, 9, 8], [9, 9, 4], [9, 9, 1], [9, 9, 5]]

b = sorted(a, key=lambda a:a[2])

#b contains the following arrays, sorted by their second index:
[[9, 9, 1], [9, 9, 2], [9, 9, 3], [9, 9, 4], [9, 9, 5], [9, 9, 8]]

Example 2: sort 2d array

Arrays.sort(myArr, (a, b) -> Double.compare(a[0], b[0]));

Example 3: python order 2d array by secode element

sorted(arr, key=lambda x: x[1])

Example 4: python sort a 2d array by custom function

>>> a = [
     [12, 18, 6, 3], 
     [ 4,  3, 1, 2], 
     [15,  8, 9, 6]
]
>>> a.sort(key=lambda x: x[1])
>>> a
[[4,  3,  1, 2], 
 [15, 8,  9, 6], 
 [12, 18, 6, 3]]

Example 5: how to bubble sort a 2d array in python

>>> blackjackList = [['harsh', '4', 'chips'], ['ahmed', '25', 'chips'], ['yousef', '1003', 'chips'], ['krushangi', '200', 'chips'], ['bombberman', '1202', 'chips']]
>>> def quicksort(arr):
...     if len(arr)==0: return []
...     if len(arr)==1: return arr
...     left = [i for i in arr[1:] if int(i[1])<int(arr[0][1])]    # for descending, exchange
...     right = [i for i in arr[1:] if int(i[1])>=int(arr[0][1])]  # these two values
...     return quicksort(left)+[arr[0]]+quicksort(right)
...
>>> quicksort(blackjackList)
[['harsh', '4', 'chips'], ['ahmed', '25', 'chips'], ['krushangi', '200', 'chips'], ['yousef', '1003', 'chips'], ['bombberman', '1202', 'chips']]