use*_*228 2 java arrays sorting
我正在尝试创建一个程序,它将对数组进行排序,但跟踪它们的原始索引.我不想更改原始数组,因此我将其复制到list [] []中.
public static void main(String[] args) {
int array[] = {17, 10, 8, 13, 5, 7, 8, 30};
int list[][] = new int[8][2];
int temp1, temp2, index, max;
for(int i=0;i<array.length; i++){
list[i][0]=array[i];
list[i][1]=i;
}
for(int i=0; i <array.length-1; i++){
max = list[i][0];
index = i;
for(int j = i+1; j<array.length;j++){
if(max<list[j][0]){
max = list[j][0];
index = j;
}
}
temp1 = list[i][0];
temp2 = list[i][1];
list[i][0]=max;
list[i][1] = index;
list[index][0]=temp1;
list[index][1]=temp2;
}
for(int n=0; n<list.length;n++){
System.out.println(list[n][0] + " " + list[n][1]);
}
}
Run Code Online (Sandbox Code Playgroud)
所以它应该打印:
30 7
17 0
13 3
10 1
8 2 2
8 6
7 5
5 4
但是当我运行它时,它会打印:
30 7
17 7
13 3
10 7
8 6
8 7
7 7
5 4
有什么建议?
为什么不是一些漂亮干净的OOP?
class Element implements Comparable<Element> {
int index, value;
Element(int index, int value){
this.index = index;
this.value = value;
}
public int compareTo(Element e) {
return this.value - e.value;
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
int array[] = {17, 10, 8, 13, 5, 7, 8, 30};
// Init the element list
List<Element> elements = new ArrayList<Element>();
for (int i = 0; i < array.length; i++) {
elements.add(new Element(i, array[i]));
}
// Sort and print
Collections.sort(elements);
Collections.reverse(elements); // If you want reverse order
for (Element element : elements) {
System.out.println(element.value + " " + element.index);
}
Run Code Online (Sandbox Code Playgroud)