我正在尝试使用合并排序对已转换为无符号长整数的 IP 地址列表进行排序。该向量包含 18647 个数字,无论是否有区别。我之前使用 C# 进行过合并排序,但这是我第一次在 C++ 中尝试它,所以我不知道是否缺少一些简单的东西。这是我目前拥有的代码:
vector<unsigned long> Sorter::mergeSort( vector<unsigned long> v){
if( v.size() <= 1 ){
return v;
}
vector<unsigned long> left, right;
int mid = v.size() / 2;
for( int i = 0; i < mid; i++ ){
left.push_back( v[i] );
}
for( unsigned int j = mid; j <= v.size(); j++ ){
right.push_back( v[j] );
}
left = Sorter::mergeSort( left );
right = Sorter::mergeSort( right );
return Sorter::merge( left, right );
}
vector<unsigned long> Sorter::merge( vector<unsigned long> left, vector<unsigned long> right){
vector<unsigned long> result;
while( left.size() > 0 || right.size() > 0 ){
if( left.size() > 0 && right.size() > 0 ){
if( left[0] <= right[0] ){
result.push_back( left[0] );
left.erase( left.begin() );
}else{
result.push_back( right[0] );
right.erase( right.begin() );
}
}else if( left.size() > 0 ){
result.push_back( left[0] );
left.erase( left.begin() );
}else if( right.size() > 0 ){
result.push_back( right[0] );
right.erase( right.begin() );
}
}
return result;
}