分布式系统中的RPC请求经常出现乱序的情况。
写一个算法来将一个乱序的序列保序输出。例如,假设起始序号是1,对于(1, 2, 5, 8, 10, 4, 3, 6, 9, 7)这个序列,输出是:
1
2
3, 4, 5
6
7, 8, 9, 10
上述例子中,3到来的时候会发现4,5已经在了。因此将已经满足顺序的整个序列(3, 4, 5)输出为一行。
要求:
1. 写一个高效的算法完成上述功能,实现要尽可能的健壮、易于维护
2. 为该算法设计并实现单元测试
#include <iostream>
#include <set>
#include <stdlib.h>
using namespace std;
void out_by_order(int input[], int n)
{
set<int> id_set;
int m = 1;
for(int i = 0; i < n; i++)
{
if(input[i] == m)
{
cout<<m;
id_set.erase(m);
while(1)
{
if(id_set.find(++m) != id_set.end())
{
cout<<','<<m;
}
else
{
cout<<endl;
break;
}
}
}
else
{
id_set.insert(input[i]);
}
}
}
void test(int a[], int n)
{
srand(time(NULL));
set<int> t;
for(int i = 0; i < n; i++)
{
while(1)
{
int rand_id = rand() % n + 1;
if(t.find(rand_id) == t.end())
{
a[i] = rand_id;
t.insert(a[i]);
break;
}
}
}
cout<<"input:(";
for(int j = 0; j < n; j++)
{
if(j == n-1)
{
cout<<a[j];
}
else
{
cout<<a[j]<<',';
}
}
cout<<")"<<endl;
out_by_order(a, 10);
}
int main(int agrc, char *argv[])
{
int a[10] = {1, 2, 5, 8, 10, 4, 3, 6, 9, 7};
out_by_order(a, 10);
cout<<endl;
cout<<"test"<<endl;
test(a, 10);
}