C++ STL中使用STD:MyGe()快速合并两个排序数组

C++程序,将两个排序的长度为n和m的数组按排序顺序合并。

null

例如:

Input : A[] = {3, 6, 9}
        B[] = {2, 7, 11}
Output : C[] = {2, 3, 6, 7, 9, 11}

Input : A[] = {1, 1, 3, 6, 9}
        B[] = {1, 2, 7, 11, 11}
Output : C[] = {1, 1, 1, 2, 3, 6, 7, 9, 11, 11}

我们在下面的帖子中讨论了其他方法 用O(1)个额外空间合并两个已排序数组 合并两个排序的数组

我们可以使用std::merge present算法头文件快速合并两个排序的数组。

下面是使用std::merge的实现

// C++ program to merge two sorted arrays
// std::merge()
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int A[] = {1, 1, 9};
int n = sizeof (A)/ sizeof (A[0]);
int B[] = {2, 7, 11, 11};
int m  = sizeof (B)/ sizeof (B[0]);
/*Merging in sorted order*/
int C[m + n];
merge(A, (A + n), B, (B + m), C);
// Print the merged array.
for ( int i = 0; i < (m + n); i++)
cout << C[i] << " " ;
return 0;
}


输出:

1 1 2 7 9 11 11 

一般来说,merge()的语法是

// Merges elements from aFirst to aLast and bFirst
// to bLast into a result and returns iterator pointing
// to first element of result
OutputItr merge(InputItr1 aFirst, InputItr1 aLast,
                InputItr2 bFirst, InputItr2 bLast,
                OutputItr result);

We can use it for array of user defined objects
also by overloading < operator.

本文由 罗希特·塔普里亚尔 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。

如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞5 分享