Wikipedia:Reference desk/Archives/Computing/2021 July 29

= July 29 =

Moving algorithm question
For work, I have needed to implement functionality to move a group of items in a list one space backward or forward. This group does not need to be consecutive, it can be in multiple parts.

So what I came up with is: The above algorithm is for moving elements backward. To move them forward, simply reverse the working list before the swapping, and then after the swapping, reverse it again.
 * Find the indices of the items to be moved. Make a list of them and ensure the list is sorted.
 * Create a working list of the indices in the original list so that the working list has one more element than the original list. This element, with index -1, is a dummy element at the start of the working list.
 * For every index in the list of indices of items to be moved, swap the element at this index with the one right before it. Note that this swapping might involve the dummy element.
 * Remove the dummy element from the working list.
 * The working list now contains the indices of the original list in the order after the move.

I have not yet tested this algorithm. Will it work, or have I made errors? J I P &#124; Talk 22:08, 29 July 2021 (UTC)