0

I'm trying to do a sorting algorithm and I need to do something like this:

arr = numpy.array([2,4,5,6])
#some function here or something
array([5,2,4,6])
#element "5" moved from position 3 to 1, and all of the others moved up one position

What I mean is I want to change an element's position (index) and move all the other elements up one position. Is this possible?

2
  • So do you know the position of the element to be taken to the first position? Commented Nov 12, 2021 at 19:36
  • It doesnt have to be the first position, but yes. Commented Nov 12, 2021 at 19:40

3 Answers 3

1

You could use numpy.roll() with a subset assignment:

arr = numpy.array([2,4,5,6])

arr[:3] = numpy.roll(arr[:3],1)

print(arr)
[5 2 4 6]
Sign up to request clarification or add additional context in comments.

3 Comments

this is also useful, thanks.
does the numpy.roll create a copy of the array or it does it in-place in the same array?
It creates a new one, hence the need to assign the result to a subset of the original
0

If you know the position/index of the element to be shifted, then you could do:

indx = 2
np.r_[arr[indx], np.delete(arr, indx)]
Out[]: array([5, 2, 4, 6])

Comments

0

You could do this in-place without the need of creating first an intermediate array of n-1 elements and then creating another final array by concatenation. Instead, you could try this:

idx = 2
tmp = arr[idx]
arr[1:idx+1] = arr[0:idx]
arr[0] = tmp

So there are more than one ways of doing this, and the choice depends upon your algorithm's constraints.

1 Comment

thankss! thats what i was looking for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.