3 回答
TA贡献1798条经验 获得超7个赞
添加 if-else 以区分正负情况。
if (a[j] < 0) {
if (a[j] < a[j+1]) {
int swap = a[j];
a[j] = a[j+1];
a[j+1] = swap;
}
} else {
if (a[j] > a[j+1] && a[j+1] > 0) {
int swap = a[j];
a[j] = a[j+1];
a[j+1] = swap;
}
}
TA贡献1820条经验 获得超9个赞
我在这里使用了库函数。但是,如果您愿意,可以使用相同的想法编写函数。
public class PostivieAsendingNegativeDesending implements Comparator<Integer> {
public static void main(String args[]) {
int fullList[] = {5, 4, 3, 2, 1, -3, -2, -30};
ArrayList<Integer> subList = new ArrayList<>();
ArrayList<Integer> subList2 = new ArrayList<>();
for (int i = 0; i < fullList.length; i++) {
if (fullList[i] < 0) {
subList2.add((fullList[i]));
} else {
subList.add(fullList[i]);
}
}
Collections.sort(subList);
Collections.sort(subList2, new PostivieAsendingNegativeDesending());
subList.addAll(subList2);
for (int i = 0; i < subList.size(); i++) {
System.out.print(subList.get(i) + " ");
}
System.out.println("");
}
@Override
public int compare(Integer n1, Integer n2) {
return n2 - n1;
}
}
TA贡献1852条经验 获得超7个赞
我建议另一种方法。您应该尝试制定精确比较必须遵守的规则。
您的要求似乎有以下规则:
正数总是在负数之前。
正数按升序排列。
负数按降序排列。是的,我说的是下降。由于较高的数字在较低的数字之前,即-2 大于-7。
警告:您使用的是嵌套 for 循环,这意味着如果数组变大,处理时间将呈指数增长。好消息是:您不需要将 for 循环嵌套到另一个 for 循环中。我建议Comparator改为写一个:
// The contract of Comparator's only method 'compare(i, j)' is that you
// return a negative value if i < j, a positive (nonzero) value if i > j and
// 0 if they are equal.
final Comparator<Integer> c = (i, j) -> { // I'm using a lambda expression,
// see footnote
// If i is positive and j is negative, then i must come first
if (i >= 0 && j < 0) {
return -1;
}
// If i is negative and j is positive, then j must come first
else if (i < 0 && j >= 0) {
return 1;
}
// Else, we can just subtract i from j or j from i, depending of whether
// i is negative or positive
else {
return (i < 0 ? j - i : i - j);
}
}
您的代码可能如下所示:
int[] a = { 5, 4, 3, 2, 1, -3, -2, -30 };
int[] yourSortedIntArray = Arrays.stream(a)
.boxed()
.sorted(c) // Your Comparator, could also added inline, like
// .sorted((i, j) -> { ... })
.mapToInt(i -> i)
.toArray();
添加回答
举报
