Fusion sorting algorithm
Is this the correct way to implement a function that uses the fusion sorting algorithm to sort a vector of doubles?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
|
#include <iostream>
#include <vector>
using namespace std;
vector<double> fusion(const vector<double>& v1, const vector<double>& v2) {
vector<double> aux(v1.size() + v2.size());
int i, j, k;
i = j = k = 0;
while(i < v1.size() and j < v2.size()) {
if(v1[i] <= v2[j]) {
aux[k] = v1[i];
++i;
}
else {
aux[k] = v2[j];
++j;
}
++k;
}
while(i < v1.size()) {
aux[k] = v1[i];
++k;
++i;
}
while(j < v2.size()) {
aux[k] = v2[j];
++k;
++j;
}
return aux;
}
void fusion_sort(vector<double>& v) {
int m = v.size()/2;
if(m != 0) {
vector<double> aux1(m);
for(int i = 0; i < aux1.size(); ++i) {
aux1[i] = v[i];
}
vector<double> aux2(v.size()-aux1.size());
for(int i = 0; i < aux2.size(); ++i) {
aux1[i] = v[aux1.size()+i];
}
fusion_sort(aux1);
fusion_sort(aux2);
v = fusion(aux1, aux2);
}
}
|
Last edited on
Topic archived. No new replies allowed.