Roy Kim
Roy Kim

Reputation: 13

How to sort an array only by using argmin()

How can I sort an array in an ascending order only by using argmin()?

For example, if I define sort_function(x) which returns the ascending order of x only by using argmin() and do:

print(sort_function(np.array([1,6,3,7]))

the result should be [1 3 6 7].

Upvotes: 0

Views: 434

Answers (1)

cs95
cs95

Reputation: 402673

Here it is, in blazing fast O(N ** 2) -

  1. Call np.argmin on the list
  2. Pop the element at that index
  3. Repeat until list is empty
def sort_function(x):
    y = list(x)
    while y:
        yield y.pop(np.argmin(y))

list(sort_function(np.array([1, 6, 3, 7])))
[1, 3, 6, 7]

Upvotes: 5

Related Questions