Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
378 views
in Technique[技术] by (71.8m points)

java - 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...