Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

int[] array (sort lowest to highest)

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!

like image 578
Austin Avatar asked Mar 20 '12 16:03

Austin


People also ask

How do you sort arrays from lowest to highest?

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.

How do I sort an int array?

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.

Is array sort ascending or descending?

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.


2 Answers

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

like image 119
Kennet Avatar answered Nov 03 '22 01:11

Kennet


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().

like image 45
matt b Avatar answered Nov 03 '22 01:11

matt b