Is there a way to reduce the time needed to find the indices of the top k largest elements from a 1D vector?
I am trying to obtain the indices of the of the largest n and smallest n elements of an array in Pytorch, and then concatenate these elements into a return array, but the time needed to do so is extremely unreasonable as the size of the array increases exponentially. 

I have tried the code that is included, as well as sorting the vector so I can just take the first and last n elements, but time is not reduced and I lose the indices of the vector, which is what I need. 

def draw(n, distr):
    return np.concatenate((np.array(distr.topk(k=int(n), largest=True).indices),
                           np.array(distr.topk(k=int(n), largest=False).indices)),
                          axis=0)


For a series of 1 dimensional arrays, varying in size from length 10 to length 2359296; furthermore, the variable n is an integer valued at 1/10th of the length of the array. My computer can compute the indices of the largest and smallest n elements of all the arrays in about 0.5 seconds. I would prefer to minimize this time as much as possible, preferably to less than 0.2 seconds

You should use torch.topk(x,k).

k=2
x = torch.arange(0,10).resize_((2,5))
print(x)
print("...")
res, ind = torch.topk(x,k)
print(res)




tensor([[0, 1, 2, 3, 4],
        [5, 6, 7, 8, 9]])
...
tensor([[4, 3],
        [9, 8]])

