进行水桶排序

时间:2018-11-20 04:27:50

标签: c++ sorting bucket-sort

我正在尝试进行存储桶排序,但是我的程序导致分段错误,我无法找到原因。我使用了两个额外的函数来帮助我对正在使用的存储区进行排序:交换函数会更改向量中的两个元素,然后是气泡交换,它会使用交换函数。给定的向量将始终有10个数字,且介于0和99之间。

template <class T>
void Sorts<T>::swap(std::vector<T> &v, int i, int j) {
T aux = v[i];
v[i] = v[j];
v[j] = aux;
}

template <class T>
std::vector<T> Sorts<T>::bubbleSort(const std::vector<T> &source) {
std::vector<T> v(source);
for(int i  = v.size() -1; i > 0; i--){
    for(int j = 0;  j<i; j++){
        if(v[j] > v[j+1]){
            swap(v, j, j+1);
        }
    }
}
return v;
}

template <class T>
std::vector<T> Sorts<T>::bucketSort(const std::vector<T> &source) {
std::vector<T> v = source;
std::vector<T> b0, b1, b2, b3, b4, b5, b6, b7, b8, b9;

for(int i = 0; i < v.size()-1; i++){
    if(v[i] >= 0 && v[i] <= 9){
        b0.push_back(v[i]);
    } else if(v[i] >= 10 && v[i] <= 19){
        b1.push_back(v[i]);
    } else if(v[i] >= 20 && v[i] <= 29){
        b2.push_back(v[i]);
    } else if(v[i] >= 30 && v[i] <= 39){
        b3.push_back(v[i]);
    } else if(v[i] >= 40 && v[i] <= 49){
        b4.push_back(v[i]);
    } else if(v[i] >= 50 && v[i] <= 59){
        b5.push_back(v[i]);
    } else if(v[i] >= 60 && v[i] <= 69){
        b6.push_back(v[i]);
    } else if(v[i] >= 70 && v[i] <= 79){
        b7.push_back(v[i]);
    } else if(v[i] >= 80 && v[i] <= 89){
        b8.push_back(v[i]);
    } else if(v[i] >= 90 && v[i] <= 99){
        b9.push_back(v[i]);
    }
}

if(!b0.empty()){
    b0 = bubbleSort(b0);    
}
if(!b1.empty()){
    b1 = bubbleSort(b1);    
}
if(!b2.empty()){
    b2 = bubbleSort(b2);
}
if(!b3.empty()){
    b3 = bubbleSort(b3);
}
if(!b4.empty()){
    b4 = bubbleSort(b4);
}
if(!b5.empty()){
    b5 = bubbleSort(b5);
}
if(!b6.empty()){
    b6 = bubbleSort(b6);
}
if(!b7.empty()){
    b7 = bubbleSort(b7);
}
if(!b8.empty()){
    b8 = bubbleSort(b8);
}
if(!b9.empty()){
    b9 = bubbleSort(b9);
}

v.clear();

for(int i = 0; i < b0.size()-1; i++){
    v.push_back(b0[i]);
}
for(int i = 0; i < b1.size()-1; i++){
    v.push_back(b1[i]);
}
for(int i = 0; i < b2.size()-1; i++){
    v.push_back(b2[i]);
}
for(int i = 0; i < b3.size()-1; i++){
    v.push_back(b3[i]);
}
for(int i = 0; i < b4.size()-1; i++){
    v.push_back(b4[i]);
}
for(int i = 0; i < b5.size()-1; i++){
    v.push_back(b5[i]);
}
for(int i = 0; i < b6.size()-1; i++){
    v.push_back(b6[i]);
}
for(int i = 0; i < b7.size()-1; i++){
    v.push_back(b7[i]);
}
for(int i = 0; i < b8.size()-1; i++){
    v.push_back(b8[i]);
}
for(int i = 0; i < b9.size()-1; i++){
    v.push_back(b9[i]);
}


return v;
}

0 个答案:

没有答案