Wikipedia:Reference desk/Archives/Computing/2021 July 29
Appearance
Computing desk | ||
---|---|---|
< July 28 | << Jun | July | Aug >> | July 30 > |
Welcome to the Wikipedia Computing Reference Desk Archives |
---|
The page you are currently viewing is a transcluded archive page. While you can leave answers for any questions shown below, please ask new questions on one of the current reference desk pages. |
July 29
[edit]Moving algorithm question
[edit]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:
- 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.
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.
I have not yet tested this algorithm. Will it work, or have I made errors? JIP | Talk 22:08, 29 July 2021 (UTC)