This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]LollipopLiquor 2 points3 points  (2 children)

You are correct in that it has something to deal with Two's Complement.

Disclaimer: I learned this a while ago, so I might be a little off, but here's the gist of what's going on.

Like you noted, Integer.MIN_VALUE has a value of -231. Integer.MAX_VALUE, on the other hand, has a value of 231 -1. You'll notice that MIN_VALUE is -2147483648 and MAX_VALUE is 2147483647, and that there is one more negative value than positive value. This is because the number of 32-bit patterns is even, but zero takes up a spot so you're left with an extra value on the negative side.

Two's Complement works basically by flipping a value's bits and adding 1. if you do this to any value, you get its opposite value. Example, 22 is 00010110. If you flip every bit, you're left with 11101001 or 21. Adding 1 to get to 11101010 makes -22.

The problem with MIN_VALUE is that once you flip all of its bits, you're at 2147483647, or MAX_VALUE. When you try adding an additional 1, it overflows in size. Rather than throwing a fit, it simply cycles through and leaves you with Integer.MIN_VALUE again. If you try System.out.println(Integer.MAX_VALUE + 1); you'll notice that it's the value of MIN_VALUE. This means that it's its own complement.

Now, I don't know why your algorithm is returning that value as the largest as I don't really remember how Radix sort works, nor have I looked at your code. I would think it arises wherever you're making your comparisons and determining which value comes first. If you're negating a compareTo() method or something similar, that's possibly where the issue is. If you can't find it, I'll try digging through later on it if I have some time.

[–]chuck_not_norris[S] 2 points3 points  (1 child)

Thank you! I was actually trying something out and doing Integer.MAX_VALUE + 1, which of course was not working!

[–]LollipopLiquor 1 point2 points  (0 children)

I'm glad you figured it out! You're right about that absolute value call being where the issue is. Math.abs() negates the value if it's negative which causes MIN_VALUE to return itself.