So I am not sure why this is becoming so hard for me, but I need to sort high to low and low to high.
For high to low I have:
int a, b;
int temp;
int sortTheNumbers = len - 1;
for (a = 0; a < sortTheNumbers; ++a) {
for (b = 0; b < sortTheNumbers; ++b) {
if (array[b] < array[b + 1]) {
temp = array[b];
array[b] = array[b + 1];
array[b + 1] = temp;
}
}
}
However, I can't for the life of me get it to work in reverse (low to high), I have thought the logic through and it always returns 0's for all the values. Any help appreciated!
The bigger picture is that I have a JTable with 4 columns, each column with entries of numbers, names, or dates. I need to be able to sort those back and forth.
Thanks!
The sort() method allows you to sort elements of an array in place. Besides returning the sorted array, the sort() method changes the positions of the elements in the original array. By default, the sort() method sorts the array elements in ascending order with the smallest value first and largest value last.
sort(int[] a, int fromIndex, int toIndex) method sorts the specified range of the specified array of ints into ascending numerical order. The range to be sorted extends from index fromIndex, inclusive, to index toIndex, exclusive.
Then, you should use the Arrays. sort() method to sort it. That's how you can sort an array in Java in ascending order using the Arrays. sort() method.
Unless you think using already available sort functions and autoboxing is cheating:
Integer[] arr =
{ 12, 67, 1, 34, 9, 78, 6, 31 };
Arrays.sort(arr, new Comparator<Integer>()
{
@Override
public int compare(Integer x, Integer y)
{
return x - y;
}
});
System.out.println("low to high:" + Arrays.toString(arr));
Prints low to high:[1, 6, 9, 12, 31, 34, 67, 78]
if you need high to low change x-y
to y-x
in the comparator
You are never visiting the last element of the array.
Also, you should be aware that bubble sort is pretty inefficent and you could just use Arrays.sort()
.
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