给定一副由 N
张牌组成的卡牌,你需要使用以下可行操作进行排序:
- 你可以看到顶部的两张牌。
- 你可以交换它们。
- 你可以将顶部的牌插入到底部。
有什么想法吗?
给定一副由 N
张牌组成的卡牌,你需要使用以下可行操作进行排序:
有什么想法吗?
以上四个步骤会一直重复,直到发生一个迭代,标记遍历整个列表而没有进行一次交换。以下是来自维基百科的示例:https://en.wikipedia.org/wiki/Bubble_sort#Step-by-step_example
现在让我们修改冒泡排序使其适应卡牌场景。我们不要把卡牌当作一副牌,而是看作一个列表。是的,随着我们修改后的冒泡排序的每次迭代,牌堆中的第一张牌将不断变化,但我们可以使得卡牌在保持牌堆顶部第一张牌的位置的同时进行移动吗?这个问题是解决问题的关键。我的意思是说,将卡牌移到牌堆底部不会改变卡牌的初始顺序,只有交换才会改变顺序。例如,考虑以下卡牌组合,其中最左侧是顶部,最右侧是底部:
注意:(*)表示标记牌。
*5 3 1 2 6
3 1 2 6 *5
5 3 1 2 6 //Mark the first card in the deck before starting
*5 3 1 2 6 //Compare 5(top card) with 3(card below it)
3 *5 1 2 6 //5 > 3 so swap
*3 5 1 2 6 //Since the marked card (5) was swapped, 3 becomes the new marked
//card to preserve original order of the deck
5 1 2 6 *3 //Top card is placed at the bottom
1 5 2 6 *3 //5 > 1 so swap
5 2 6 *3 1 //Put 1 at the bottom
2 5 6 *3 1 //5 > 2 so swap
5 6 *3 1 2 //Put 2 at the bottom
5 6 *3 1 2 //5 < 6 so no swap
6 *3 1 2 5 //Put 5 at the bottom
*3 1 2 5 6 //Marked card is second to top card, so put 6 at the bottom
//Marked card is now at the top, so new iteration begins
进入第二次迭代之前,我想指出,如果您运行了原始冒泡排序算法,那么一个迭代的结果序列与我们修改后算法的一个迭代的结果序列将是相同的。
第二次迭代:
*3 1 2 5 6 //3 > 1, so swap
*1 3 2 5 6 //Remark accordingly since the former marked card was swapped
3 2 5 6 *1 //Place 1 at the bottom
2 3 5 6 *1 //3 > 2, so swap
3 5 6 *1 2 //Place 2 at the bottom
3 5 6 *1 2 //3 < 5 so no swap
5 6 *1 2 3 //Place 3 at the bottom
5 6 *1 2 3 //5 < 6 so no swap
6 *1 2 3 5 //Place 5 at the bottom.
*1 2 3 5 6 //Since marked card is second to top card, place 6 at the bottom and end iteration
第三轮迭代:
*1 2 3 5 6 //1 < 2 so no swap
2 3 5 6 *1 //Place 1 at the bottom
3 5 6 *1 2 //2 < 3 so no swap and place 2 at the bottom
5 6 *1 2 3 //3 < 5 so no swap and place 3 at the bottom
6 *1 2 3 5 //5 < 6 so no swap and place 5 at the bottom
*1 2 3 5 6 //Since marked card is second to top card, place 6 at the bottom and end iteration.
我们现在知道要结束算法,因为整个迭代过程中没有发生任何交换,所以牌堆现在已经排序。至于运行时间,在交换方面,最坏情况是发生最大数量的迭代,即n(牌堆大小)次。对于每次迭代,最坏情况下需要进行的交换次数也是n次。因此,大O表示法为n * n或O(n ^ 2)。
O(n^n)
或者类似这样可怕的时间复杂度完成... - shapiro yaacov