Sorting a deck of cards with a minimum number of moves

We have n cards with each card numbered from 1 to n.

All cards are randomly shuffled.

We are only allowed the MoveCard (n) operation, which moves the card with the value n to the top of the pile.

We need to sort a bunch of cards with a minimum number of MoveCard operations.

The naive approach I can think of starts with MoveCard (n), MoveCard (n-1), MoveCard (n-2) ... MoveCard (1).

This approach will solve the problem in n MoveCard operations.

But we can optimize it.

For example, if the input is similar: 3 1 4 2

According to my approach:

                4 3 1 2

                3 4 1 2

                2 3 4 1

                1 2 3 4

MoveCard operations are 4.

But we can solve this problem with a minimum number of moves:

Optimized solution:

                3 1 4 2

                2 3 1 4

                1 2 3 4

MoveCard operations are 2.

, , .

, , .

:

         3 1 4 2

2 2 3 1 4 {2,3 4 }

1, . 1 2 3 4.

+3
1

. , . , . , , , .

, n. n-1 n , n-1 . n-- .

:

2 4 3 1    // 3 comes after 4, so move 3
3 2 4 1    // move 2
2 3 4 1    // move 1
1 2 3 4    // done after 3 moves

3 1 4 2    // 3 comes -before- 4, so leave it alone. 2 comes after 3, move it
2 3 1 4    // move 1
1 2 3 4    // done after 2 moves

, , "" . .

- O (n ^ 2), , . , , , , .

n-1, n.

, , , , . , 3, 4, 3 . , 3 , .

+1

All Articles