问题描述
我正在尝试使用Counting Sort和double向量在C ++中实现RadixSort。输入应为10位数(0-9),以空格分隔。它应该对输入进行排序。例如:
输入:
3
1 2 3 5 6 3 0 0 1 1
0 3 1 2 4 3 2 1 2 3
0 0 0 0 0 2 1 2 4 9
输出:
0 0 0 0 0 2 1 2 4 9
0 3 1 2 4 3 2 1 2 3
1 2 3 5 6 3 0 0 1 1
为清楚起见,我想确保CountingSort函数正常运行。当我使用大量矢量对其进行一些测试时,它会失败。 (我输入了上面的示例,但是得到了正确的输出)。我了解我使用双向量的方法可能并不理想,并且您可能会说我应该使用数组或数组的向量,等等。但是如果我们可以坚持使用vector
#include <iostream>
#include <cmath>
#include <stdlib.h>
#include <vector>
#include <string>
using namespace std;
void print(vector<vector<int>> v){
for(int i = 0; i < v.size(); i++){
for(int j = 0; j < v[i].size(); j++){
cout << v[i][j] << ";";
}
cout << "" << endl;
}
}
void countingSort(vector<vector<int>> v,int num_vectors,int col,int count){
vector<vector<int>> output;
for(int i = 0; i < num_vectors; i++){
vector<int> new_vect;
for(int j = 0; j < 10; j++){
new_vect.push_back(0);
}
output.push_back(new_vect);
}
int C[10] = {0};
//Counting how many repeated values are in column col,histogram
for (int i = 0; i < num_vectors; i++){
C[v[i][col]] = C[v[i][col]] + 1;
}
//cumulative histogram
for (int i = 1; i < 10; i++){
C[i] = C[i] + C[i - 1];
}
//Sorting
for (int i = num_vectors - 1; i >= 0; i--){
int index = C[v[i][col]] - 1;
output[ index ] = v[i];
C[v[i][col]] = C[v[i][col]] - 1;
}
if(count == 10){
print(output);
}
}
void radixSort(vector<vector<int>> v,int num_vectors){
int count = 0;
for(int col = 9; col > -1 ; col--){
count++;
countingSort(v,num_vectors,col,count);
}
}
void input(){
int num_vectors,str_to_int;
string input_values; //digits 0 - 9 separated by spaces
cin >> num_vectors;
vector<vector<int>> v;
for(int i = 0; i < num_vectors; i++){
ws(cin); //Clears whitespace so that getline can run
std::vector<int> newVect;
getline(cin,input_values,'\n');
for(int j = 0; j < 10; j++){
char digit = input_values[j*2]; // "0 1 2 3 4 5 6 7 8 9"
str_to_int = (int)digit % 48;
newVect.push_back(str_to_int);
}
v.push_back(newVect);
}
radixSort(v,num_vectors); //v[0...n],v[0] < v[n]
}
int main(){
input();
return 0;
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)