int[] 数组(从低到高排序) [英] 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.
从高到低,我有:
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;
}
}
}
但是,我一生都无法让它反向工作(从低到高),我已经仔细考虑了逻辑,并且对于所有值它总是返回 0.任何帮助表示赞赏!
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!
更大的图景是我有一个包含 4 列的 JTable,每列都有数字、名称或日期条目.我需要能够来回对它们进行排序.
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.
谢谢!
推荐答案
除非你认为使用已经可用的排序函数和自动装箱是作弊:
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));
打印从低到高:[1, 6, 9, 12, 31, 34, 67, 78]
如果你需要从高到低在比较器中将 x-y
改为 y-x
if you need high to low change x-y
to y-x
in the comparator
这篇关于int[] 数组(从低到高排序)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!