I'm trying to make program to sort numbers higher to lower from left to right, and it seems to glitch whenever the number increments too soon. I tried a handful of inputs:
42145 Sorted to 54421, correct;
41245 Sorted to 54221, wrong but almost right;
1021 Sorted to 2210, wrong but almost right;
254321234 Sorted to 555555552, very much wrong.
Is it just my method of sorting or did I do something wrong? Code:
#include <iostream>
#include <vector>
#include <math.h>
#include <string>
#include <sstream>
using namespace std;
uint64_t descend(uint64_t num) {
vector<uint64_t> numVect;
int numLength = 1;
uint64_t numTmp = num;
stringstream output;
uint64_t result;
//Find the length of the entered number
while (true) {
numTmp /= 10;
if (numTmp > 0)
numLength++;
else
break;
}
//Make the entered number into a vector
for (int i = 1; i < numLength + 1; i++) {
numTmp = num / pow(10, numLength - i);
numTmp %= 10;
numVect.push_back(numTmp);
}
//Sort the numbers in the vector
for (int j = 0; j < numLength; j++) {
numTmp = numVect[j];
for (int i = j; i < numLength; i++) {
if (numTmp < numVect[i]) {
numVect.insert(numVect.begin()+j, numVect[i]);
numVect.erase(numVect.end() - 1);
break;
}
}
}
//Convert the vector to a regular number and return
for (int i = 0; i < numLength; i++) {
output << numVect[i];
}
output >> result;
return result;
}
int main() {
uint64_t output;
cin >> output;
output = descend(output);
cout << "output: " << output << endl;
return 0;
}