Context
I have an SQL table containing items.
id name order
==============
1 book 3
2 table 1
3 chair 2
4 bag 4
So as we can see, the items are sorted in this order:
- table
- chair
- book
- bag
Question
Given a form where a user can reorder an item by selecting another item as reference and a placement (before or after), what is the most optimal algorithm to reorder items so that the order is re-generated from 1 to N (where N is the amount of items)?
By "optimal" I mean consuming the least amount of resources (so the O complexity should be the closest possible to O(N)).
If possible, provide a pseudo-code algorithm (if you prefer writing in your prefered programming language it's fine for me as well).
Example
Here is a picture with the form I intent to use if you need a mental model to better grasp on this challenge:
In action, given this dataset
id name order
==============
1 book 3
2 table 1
3 chair 2
4 bag 4
Case 1: the user wants to place the bag before the table. The result will be:
id name order
==============
1 book 4
2 table 2
3 chair 3
4 bag 1
Case 2: Keeping this dataset, the user now decides to place the table after the chair. The result will be:
id name order
==============
1 book 4
2 table 3
3 chair 2
4 bag 1
Case 3: this time the user would like to place the book before the chair. The result will be:
id name order
==============
1 book 2
2 table 4
3 chair 3
4 bag 1
Case 4: the user request to put the bag before the chair. The result will be:
id name order
==============
1 book 1
2 table 4
3 chair 3
4 bag 2