Home > Mobile >  Python Sort Array
Python Sort Array

Time:03-04

Is it possible to sort an array with the smallest values on the bottom left and the highest on the top right?

For example :

I've this array :

[[-1.  1.  1.]
 [ 1.  1.  1.]
 [ 1.  1.  1.]
 [ 1.  1.  1.]
 [ 1.  1.  1.]
 [-1.  1.  1.]]

the sort would be like

[[1.  1.  1.]
 [ 1.  1.  1.]
 [ 1.  1.  1.]
 [ 1.  1.  1.]
 [-1.  1.  1.]
 [-1.  1.  1.]]

An other example :

[[-1.  1.  1.]
 [ 1.  1.  1.]
 [ 1.  1.  1.]
 [ 4.  3.  1.]
 [ 1.  1.  1.]
 [-1.  1.  1.]]

Would be :

[[ 1.  1.  4.]
 [ 1.  1.  3.]
 [ 1.  1.  1.]
 [ 1.  1.  1.]
 [-1.  1.  1.]
 [-1.  1.  1.]]

I Tried Numpy sort :

MyArray.sort()

But it seems not ordering this way.

CodePudding user response:

import numpy as np

x = np.random.rand(6,3)

print(x)

def eiffel_tower_sort(a):
    b = a.flatten()
    b.sort()
    return np.flipud(b.reshape(a.shape, order='F'))

print(eiffel_tower_sort(x))
# randomized / unsorted
[[0.45884748 0.36774746 0.82728461]
 [0.46473908 0.22377053 0.43772489]
 [0.3596408  0.89647436 0.43567059]
 [0.10431368 0.06733271 0.26813345]
 [0.45886791 0.57112807 0.51780818]
 [0.27032551 0.77706324 0.32331996]]

# sorted
[[0.32331996 0.45886791 0.89647436]
 [0.27032551 0.45884748 0.82728461]
 [0.26813345 0.43772489 0.77706324]
 [0.22377053 0.43567059 0.57112807]
 [0.10431368 0.36774746 0.51780818]
 [0.06733271 0.3596408  0.46473908]]

CodePudding user response:

This will get you a sorted array that is sorted from smallest to largest, running from the bottom left up each column till the top right.

import numpy as np

# Just some code to get a random, unsorted array
unsorted = np.arange(0,20)
np.random.shuffle(unsorted)
unsorted = unsorted.reshape((5,4))
print("Original Array:")
print(unsorted)

# Get the shape of the original array
array_shape = unsorted.shape
# Flatten, sort, reshape and rotate.
sorted_array = np.rot90(np.sort(unsorted.flatten()).reshape(array_shape[::-1]))

print("Sorted Array:")
print(sorted_array)

Output:

Original Array:
[[18 12  9 15]
 [ 1 19 17 13]
 [16  0 11  7]
 [ 2  6  5 14]
 [ 4  8  3 10]]
Sorted Array:
[[ 4  9 14 19]
 [ 3  8 13 18]
 [ 2  7 12 17]
 [ 1  6 11 16]
 [ 0  5 10 15]]

I'd have to give this some more thought to get a 'diagonally sorted' array.

  • Related