I need a sorting algorithm which operates on a single, pre-populated array, and which is limited to perform only one type of write operation:
O=Move an item X to index Y. The elements on subsequent positions are shifted 1 position.
The algorithm must be optimized for the least possible number of operations O. Read operations are infinitely cheaper than write operations. Temporary helper lists are also cheap.
Edit: It might be more correct to call it a linked list, because of its behaviour, although the implementation is hidden for me.
Background:
The thing is I’m working against a Google API which only allows me to perform this operation on their lists. The operation is a web service call. I want to minimize the number of calls. You can assume the sorting program (the client) has a copy of the list in memory before starting, so there is no need to perform read operations against the service – only write. You can of course also do any amount of temporary list actions locally before performing the service calls, including duplicating the list or using existing .NET sort functions.
How do I proceed here? Is there a known algorithm I can use here?
Failed attempt:
I have already implemented a dumb algorithm, but it is not optimal for all cases. It works well when the list is like this:
List A = [2,3,4,5,6,7,8,9,1]
It goes like this:
- Is list sorted? No
- Find element that belongs at position 0: “1”
- Move Element “1” to position 0
- (New list state A1:
[1,2,3,4,5,6,7,8,9]) - Is list sorted? Yes. End
…But when the list is like this, I get into trouble:
List B = [9,1,2,3,4,5,6,7,8]
- Is list sorted? No
- Find element that belongs at position 0: “1”
- Move Element “1” to position 0
- (New list state B1:
[1,9,2,3,4,5,6,7,8]) - Is list sorted? No
- Find element that belongs at position 1: “2”
- Move Element “2” to position 1
- (New list state B2:
[1,2,9,3,4,5,6,7,8]) - …you can see where I’m going here…
Compute the longest increasing subsequence of the array. Perform a write operation for each element that is not present in the sequence.
EDIT: Adding an example
Let the numbers in the input array be
1 3 2 7 4 8 6 5 9. A longest increasing sequence is1 2 4 6 9. When computing this sequence store the indexes of the elements that occur in the sequence. Then it is straightforward to travel through the original array and find the elements not present in the sequence. In this case they are3 7 8 5. For each of these elements perform a write operation that places them in the appropriate position. So the sequence of modifications of the array would be: