Here's a way to sort in-place without boxing/unboxing. These approaches have the disadvantage of either requiring boxing/unboxing (so that a Comparator can be used), or that new arrays are needed to accommodate the elements. There are different ways to create a sorted array of ints out of an unsorted one using streams, as the other answers show. Thus, using negation in an attempt to perform a descending sort doesn't work.įinally, boxing and using a Comparator works, but it's considerably slower, and it allocates a separate object for (almost) every int value. This is asymmetric, because the negation of MIN_VALUE is MIN_VALUE. It reflects the table at zero, so the negation of zero is zero, the negation of -1 is 1, etc. Note that this differs from negation - which doesn't do the right thing here. Thus, an ascending sort on the complemented values is a descending sort on the original values. Also, another complement will restore the original value. You can see by inspection that this reflects the table about a pivot point between -1 and 0, so -4 becomes 3, -3 becomes 2, etc. The bitwise complement operator ~ inverts every bit. Consider if ints were to have only three bits. To see this, you have to understand that Java ints use two's complement representation. This provides an exact, lossless reversal of the ordering of every possible int value. This works by doing a bitwise complement of the int values before and after the sort. The runtime is dominated by the sorting for an array of any significant size, so it's unlikely to be noticeable. This is a tiny bit slower than sorting ascending and then reversing the array it has to do an extra pass over the array. Here's a pretty way to sort descending: tAll(array, i -> ~array) To sort ascending, simply do Arrays.sort(array)
0 Comments
Leave a Reply. |
Details
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |