例如我有这个数组
int[] a = {6,10,16,11,7,12,3,9,8,5};
我想像这样对其索引进行排序
[6,9,0,4,8,7,1,3,5,2]
所以我可以使用索引将 a 从最小到最大值排序。
在我的代码中我得到了这个
[6, 9, 4, 8, 7, 4, 5, 6, 6, 6]
这是我的代码
int[] a = {6,10,16,11,7,12,3,9,8,5};
int[] indeks = indekssortering(a);
System.out.println(Arrays.toString(indeks));
public static int[] indekssortering(int[] a){
int[] indeks = new int[a.length];
int m = 0;
boolean finnes = false;
boolean nyVerdi = false;
int n = 0;
for (int j = 0; j < a.length; j++) {
for (int i = m+1; i < a.length ; i++) {
if(a[m] > a[i]){
for (int k = 0; k < j; k++) {
if(indeks[k] == i) finnes = true; //check if the same position is saved before
}
if(!finnes){ // if not so its the next minimum value
m = i;
} else {
nyVerdi = true; // if didnt find match then the value used to compare is the next minimum
}
}
finnes = false;
}
indeks[j] = m;
if(nyVerdi) n=n+1;
nyVerdi = false;
m=0+n;
}
return indeks;
}
我需要帮助才能使该代码正常工作或找到比这更好的想法。
我试图做的是。
将所有值与第一个值进行比较,获取最小值并将位置保存到数组(索引)中。在保存之前,我做了for循环来检查之前是否添加过这个位置。如果没有值大于用于比较的值,则意味着它是下一个小值。
我有些是对的,有些是错的。我认为我需要改变这个想法并找到更好的解决方案。