for(int i = 0; i < distance.length; i++) {
for (int j = 0; j < distance.length; j++) {
if (distance[i] == distance[j]) {
if (x[i] > x[j]) {
x = swapInt(x, j, i);
input = swapString(input, j, i);
}
}
}
}距离表示点到原点的距离
X是点的x坐标。
输入是用户对点的原始输入
如果这些点的距离相同,我想让这个循环按照x坐标的升序排列这些点。但是,当我运行它时,它是以降序排列的。
我该怎么解决这个问题呢?
public static int[] swapInt (int[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
return a;
}发布于 2012-04-14 22:54:42
变化
if (x[i] > x[j]) {至
if (x[i] < x[j]) {这将改变排序顺序:在原始中,如果第i个大于j‘’th,则交换两个值;现在,如果相反,则交换两个值:j‘’th大于i‘’th
发布于 2012-04-14 23:07:36
我更喜欢下面的方式,因为它更干净,可读性更好。
class Distance implements Comparable{
int x;
int y;
@Override
public int compareTo(Object o) {
Distance other=(Distance)o;
if(this.distanceFromOrigin() > other.distanceFromOrigin())
return 1;
else if(this.distanceFromOrigin() < other.distanceFromOrigin())
return -1;
else
return this.x - other.x;
}
int distanceFromOrigin(){
return x*x+y*y;
}}
现在创建一个距离数组/列表,并使用Collections.sort获得所需的顺序。
https://stackoverflow.com/questions/10154481
复制相似问题