0
How can i sort an integer number in Java?
i want to sort (472964) and print it like this (244679). i can't use arrays or any other var types except integer.
12 Respuestas
+ 4
Oo cool jeth👍
but i will trace it out,might take some time.
but thanx😊
edit: thanx Tiago ☺
+ 3
Search for Collections methods and Bubble sort.
The logic can be seen here:
http://stackoverflow.com/questions/33971256/how-to-sort-integer-digits-in-ascending-order-without-strings-or-arrays
+ 2
java gave us so many functions ,Y the hard way :/
+ 2
@Jeth,do u have the link for explanation of this code,send the link pls...
+ 1
Well, it will be much more easy with arrays. But...
int num1, num2, num3, num4, num5, num6, inputNum, sortedNum, tempNum;
inputNum = 472964;
num1 = inputNum/100000;
num2 = (inputNum/10000)%10;
num3 = (inputNum/1000)%10;
num4 = (inputNum/100)%10;
num5 = (inputNum/10)%10;
num6 = inputNum%10;
for (int i = 0; i < 6; i++) {
if (num2 < num1) {
tempNum = num1;
num1 = num2;
num2 = tempNum;
}
if (num3 < num2) {
tempNum = num2;
num2 = num3;
num3 = tempNum;
}
if (num4 < num3) {
tempNum = num3;
num3 = num4;
num4 = tempNum;
}
if (num5 < num4) {
tempNum = num4;
num4 = num5;
num5 = tempNum;
}
if (num6 < num5) {
tempNum = num5;
num5 = num6;
num6 = tempNum;
}
}
sortedNum = num1*100000 + num2*10000 + num3*1000 + num4*100 + num5*10 + num6;
System.out.println(sortedNum);
+ 1
It is my own code, i just writed it by myself so if you need an explanation - ask what you want to know.
+ 1
Well, then you should look at the link above. My code is not optimal and works bad with zeroes in number, there is a better algorithm in the link with explanation.
0
it's an assignment. 😥
0
good work @Jeth
i need a dynamic code that reada an integer feom the console. i need it to work with any number, whether it's 21 or 48294782817839.
0
see my code
https://code.sololearn.com/cjwAkp0JNJeb/?ref=app
0
thank you everybody. but i wrote an easy and efficient code. just did a bubble sort for the digits in the number. if anyone wants the code,et me know.
0
Yeah you can convert an integer into an int! Its called unboxing. You usually see it happening during arraylists.