PROJECT EULER · #0524
First Sort II
Consider the following algorithm for sorting a list:
- 1. Starting from the beginning of the list, check each pair of adjacent elements in turn.
- 2. If the elements are out of order:
- a. Move the smallest element of the pair at the beginning of the list.
- b. Restart the process from step 1.
- 3. If all pairs are in order, stop.
For example, the list
( and are out of order so move to the front of the list) ( and are out of order so move to the front of the list) ( and are out of order so move to the front of the list) ( and are out of order so move to the front of the list) ( and are out of order so move to the front of the list) (The list is now sorted)
Let
We can list all permutations
Let
For
| P | I4(P) | F(P) | |
|---|---|---|---|
| {1, 2, 3, 4} | 1 | 0 | Q(4, 0) = 1 |
| {1, 2, 4, 3} | 2 | 4 | Q(4, 4) = 2 |
| {1, 3, 2, 4} | 3 | 2 | Q(4, 2) = 3 |
| {1, 3, 4, 2} | 4 | 2 | |
| {1, 4, 2, 3} | 5 | 6 | Q(4, 6) = 5 |
| {1, 4, 3, 2} | 6 | 4 | |
| {2, 1, 3, 4} | 7 | 1 | Q(4, 1) = 7 |
| {2, 1, 4, 3} | 8 | 5 | Q(4, 5) = 8 |
| {2, 3, 1, 4} | 9 | 1 | |
| {2, 3, 4, 1} | 10 | 1 | |
| {2, 4, 1, 3} | 11 | 5 | |
| {2, 4, 3, 1} | 12 | 3 | Q(4, 3) = 12 |
| {3, 1, 2, 4} | 13 | 3 | |
| {3, 1, 4, 2} | 14 | 3 | |
| {3, 2, 1, 4} | 15 | 2 | |
| {3, 2, 4, 1} | 16 | 2 | |
| {3, 4, 1, 2} | 17 | 3 | |
| {3, 4, 2, 1} | 18 | 2 | |
| {4, 1, 2, 3} | 19 | 7 | Q(4, 7) = 19 |
| {4, 1, 3, 2} | 20 | 5 | |
| {4, 2, 1, 3} | 21 | 6 | |
| {4, 2, 3, 1} | 22 | 4 | |
| {4, 3, 1, 2} | 23 | 4 | |
| {4, 3, 2, 1} | 24 | 3 |
Let
Find
Write-up coming later
The complete problem is available here. An approach, code, and answer will be added later.