I'm trying to sort the digits of an integer of any length in ascending order without using Strings, arrays or recursion.
Example:
Input: 451467
Output: 144567
I have already figured out how to get each digit of the integer with modulus division:
int number = 4214;
while (number > 0) {
IO.println(number % 10);
number = number / 10;
}
but I don't know how to order the digits without an array.
Don't worry about the IO
class; it's a custom class our professor gave us.
Count the number of digits in each number. The number with the least number of digits is the smallest. Write it first. Continue this till all the numbers left for comparison have the same number of digits.
Suppose for example, 81, 97, 123, 137 and 201 are arranged in ascending order. Vice-versa while arranging numbers from the largest number to the smallest number then the numbers are arranged in descending order. Suppose for example, 187, 121, 117, 103 and 99 are arranged in descending order.
There's actually a very simple algorithm, that uses only integers:
int number = 4214173;
int sorted = 0;
int digits = 10;
int sortedDigits = 1;
boolean first = true;
while (number > 0) {
int digit = number % 10;
if (!first) {
int tmp = sorted;
int toDivide = 1;
for (int i = 0; i < sortedDigits; i++) {
int tmpDigit = tmp % 10;
if (digit >= tmpDigit) {
sorted = sorted/toDivide*toDivide*10 + digit*toDivide + sorted % toDivide;
break;
} else if (i == sortedDigits-1) {
sorted = digit * digits + sorted;
}
tmp /= 10;
toDivide *= 10;
}
digits *= 10;
sortedDigits += 1;
} else {
sorted = digit;
}
first = false;
number = number / 10;
}
System.out.println(sorted);
it will print out 1123447
.
The idea is simple:
That version of the algorithm can sort in both asc in desc orders, you just have to change the condition.
Also, I suggest you to take a look at so-called Radix Sort, the solution here takes some ideas from radix sort, and I think the radix sort is the general case for that solution.
My algorithm of doing it:
int ascending(int a)
{
int b = a;
int i = 1;
int length = (int)Math.log10(a) + 1; // getting the number of digits
for (int j = 0; j < length - 1; j++)
{
b = a;
i = 1;
while (b > 9)
{
int s = b % 10; // getting the last digit
int r = (b % 100) / 10; // getting the second last digit
if (s < r)
{
a = a + s * i * 10 - s * i - r * i * 10 + r * i; // switching the digits
}
b = a;
i = i * 10;
b = b / i; // removing the last digit from the number
}
}
return a;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With