You are given an integer 51234 (say) we need to sort the digits of a number the output will be 12345.
How to do it without using array ?
// Bubblesort
long sortNum(long n) {
while (true) {
long a = n % 10, p = 9;
bool s = false;
for (long r = n / 10; r; r/= 10) {
long b = r % 10;
if (a < b) {
n -= p * (b - a);
s = true;
} else a = b;
p *= 10;
}
if (!s) return n;
}
}
#include
int main(int argc, char **argv) {
if (argc > 1) {
long n = strtol(argv[1], 0, 0);
std::cout << "Unsorted: " << n << std::endl;
n = sortNum(n);
std::cout << "Sorted: " << n << std::endl;
}
return 0;
}
$ g++ -Wall -Wextra bubble-int.cpp && ./a.exe 183974425
Unsorted: 183974425
Sorted: 123445789