自定义一个类,用于存储数值和下标,类似C语言的结构体
public class MyArray {
private int subscript;
private double value;
public int getSubscript() {
return subscript;
}
public void setSubscript(int subscript) {
this.subscript = subscript;
}
public double getValue() {
return value;
}
public void setValue(double value) {
this.value = value;
}
}
实现:
MyArray[] a = new MyArray[5];
for (int i = 0; i < a.length; i++) {
a[i] = new MyArray();
a[i].setValue(Math.random());
a[i].setSubscript(i);
}
double tmp = 0;
int tmpj = 0;
for (int j = 0; j < a.length; j++) {
for (int i = 0; i < a.length-j-1; i++) {
if (a[i].getValue()
tmp = a[i].getValue();
a[i].setValue(a[i+1].getValue());
a[i+1].setValue(tmp);
//置换原来的脚标
tmpj = a[i].getSubscript();
a[i].setSubscript(a[i+1].getSubscript());
a[i+1].setSubscript(tmpj);
}
}
}
//输出排序后的值和下标
for (int i = 0; i < a.length; i++) {
System.out.print(a[i].getValue()+"\t");
System.out.println(a[i].getSubscript()+"\t");
}