Sorting a deque using limited operations?

后端 未结 3 704
庸人自扰
庸人自扰 2021-01-13 02:46

Hi I came across a question in the Algorithms 4th Edition by Robert Sedgewick.

Dequeue sort. Explain how you would sort a deck of cards, with the res

3条回答
  •  不思量自难忘°
    2021-01-13 03:37

    Rather than thinking of the deck having a top and a bottom, imagine that the deck of cards is arranged in a ring. You can imagine having a marker that you place between two specific cards, which then corresponds to the top of the deck. Your operations of "swap the top two cards" is then swapping the two cards to the left of the marker, and the operation of "move the top of the deck to the bottom" then corresponds to moving the marker one step to the left.

    Given this, you can naturally adapt bubble sort to work in this setup. Permanently mark one of the positions in the ring as the start point. Then, repeatedly do the following: if the two cards to the left of the marker are out of order, swap them. Then, move the marker one step to the left. As an exception to the rule, if the marker is one step before the marker's initial position, don't do the comparison. If you go around the circle without exchanging anything, you're done!

    In pseudocode, this would look as follows:

    repeat the following until no swaps are made:
        counting from i = 1 to n - 1, inclusive:
           if the top two cards are out of order, swap them.
           move the top card of the deck to the bottom.
        then, move the top card of the deck to the bottom.
    

    Hope this helps!

提交回复
热议问题