Forums Register Login

Sorting numbers using Compare method

+Pie Number of slices to send: Send
Hello,

I have implemented a Doubly Linked List to sort elements (integer or character) into ascending order. My problem is that it reads 34 as 3, 56 as 5, 78 as 7 and so on. It also behaves the same for letters like AB is A and TY is T...etc.
I have converted the object elements into strings so that i can use the compare method like this:



where the current is the DLNode current node and next is the DLNode next node after current node.

Can anyone figure out why it's doing this?

Thanks in advance.
+Pie Number of slices to send: Send
Do you do any manipulation of the String in the class? It appears that you are removing the last character.
+Pie Number of slices to send: Send
Hi,
thanks for the reply. No there is no string manipulation, only string the objects such as (String)current.getElement().
+Pie Number of slices to send: Send
Can you post the code?
+Pie Number of slices to send: Send
Is this the kind of thing you get?

If so, that is the proper sort order for strings, but not for numbers. You have to right justify strings that are numbers to make them sort in numeric order. I used zeros to pad - spaces also work but they're a bit harder to see.

So your choices are to right justify strings or convert strings to some numeric type like Integer. One challenge with right justification is making sure your numbers are wide enough for the longest possible value. For positive ints that might be 10 digits. See what this line does:
+Pie Number of slices to send: Send
You could also write your own Comparator to order the Collection.

For instance:



The output is: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Regards,
Edwin Dalorzo
+Pie Number of slices to send: Send
thanks everyone, i padded out my numbers and they are in order now.
thanks!
+Pie Number of slices to send: Send
The custom comparator is a pretty good idea. I just got tired of typing before I got to it. (Honest!) It has more overhead doing two conversions on every compare, but it's reusable in other future projects is a more "correct" solution.
The airline is called "Virgin"? Don't you want a plane to go all the way? This tiny ad will go all the way:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 1670 times.
Similar Threads
a simple but complex problom
Tree Structure + Depth First Traversal?
Linked List Help
a simple problom
A challenge
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 29, 2024 02:52:52.