標籤:style blog http color os io
本文為senlie原創,轉載請保留此地址:http://blog.csdn.net/zhengsenlie
merge (應用於有序區間)
--------------------------------------------------------------------------
描述:將兩個經過排序的集合S1和S2,合并起來置於另一段空間。所得結果也是一個有序(sorted)序列
思路:
1.遍曆兩個序列直到其中一個結束了
2.如果序列一的元素較小,將它放到結果序列中,並前進 1
3.如果序列二的元素較小,將它放到結果序列中,前前進 1
4.遍曆結束後,將還沒有遍曆完的序列複製到結果序列的尾部
複雜度:O(m+n)
源碼:
template <class InputIterator1, class InputIterator2, class OutputIterator>OutputIterator merge(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result) { while (first1 != last1 && first2 != last2) { if (*first2 < *first1) { *result = *first2; ++first2; } else { *result = *first1; ++first1; } ++result; } return copy(first2, last2, copy(first1, last1, result)); // 之前一直不懂為什麼 copy 之類的演算法要返回一個指向 操作完後的序列的 last 的迭代器。這行代碼很好地解釋了原因}
樣本:
int main(){ int A1[] = { 1, 3, 5, 7 }; int A2[] = { 2, 4, 6, 8 }; const int N1 = sizeof(A1) / sizeof(int); const int N2 = sizeof(A2) / sizeof(int); merge(A1, A1 + N1, A2, A2 + N2, ostream_iterator<int>(cout, " ")); // The output is "1 2 3 4 5 6 7 8"}