[這是一個面試問題。我找不到重複。]就地排序有2個排序子陣列的數組
一個數組包含兩個子排序數組。給出一個就地算法來排序兩個子數組。
爲例如:I/P:1 4 5 7 8 9 2 3 6 10 11 O/P:1 2 3 4 5 6 7 8 9 10 11
我在就地方面認爲合併排序,插入排序(因爲子數組已經排序)和快速排序的方面,但不能想到一個解決方案,它比使用標準排序方法提供了更好的複雜性。
請幫我找一個算法,它允許我們利用排序後的子數組屬性,並導致比在輸入上運行Quicksort更好的時間複雜度。
這是合併排序模擬我想,用這個例子:
1) For position 0, Comparing 1 & 2, 1 is smaller let it stay at it's original place
2) For position 1, Comparing 2 & 4, 2 is smaller so swap 2 and 4
3) For position 2, Comparison now is between 4 and 3 (5 > 4 anyways) swap 3 and 5
4) For position 3, Comparison between 4 & 5, swap 4 and 7
5) For position 4, Comparison between 7 & 5, swap 8 and 5
6) For position 5, Comparison between 7 & 8 (OUCH!!) it should have been between 7 & 6
看來,這個問題類似於排序矩陣,其中就地合併過於複雜的排序行。
再考慮合併排序。 – phs 2013-03-14 03:21:48
可能重複的[如何使用O(n)時間和O(1)空間成本合併兩個排序的整數數組](http://stackoverflow.com/questions/2126219/how-to-merge-two-sorted -integer-array-in-place-using-on-time-and-o1-space-co) – 2013-03-14 08:17:54