如何对数组进行排序(索引)以使用这些索引将原始数组从最小到最大值排序

2024-05-07

例如我有这个数组

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循环来检查之前是否添加过这个位置。如果没有值大于用于比较的值,则意味着它是下一个小值。 我有些是对的,有些是错的。我认为我需要改变这个想法并找到更好的解决方案。


这里有一个经典冒泡排序算法 https://en.wikipedia.org/wiki/Bubble_sort修改实现以对索引进行排序

您正在寻找的实际上是任何排序算法int [] array。互联网上有无穷无尽的实现列表。然后将比较更改为array[result[i]]并交换值result not in array itseft.

static int[] sort(int[] array) {
    final int size = array.length;

    final int[] result = new int[size];
    for (int i = 0; i < size; i++)
        result[i] = i;

    boolean sorted;
    do {
        sorted = true;
        int bubble = result[0];
        for (int i = 0; i < size - 1; i++) {
            if (array[bubble] > array[result[i + 1]]) {
                result[i] = result[i + 1];
                result[i + 1] = bubble;
                sorted = false;
            } else {
                bubble = result[i + 1];
            }
        }
    } while (!sorted);

    return result;
}

result arrays for your input data is [6, 9, 0, 4, 8, 7, 1, 3, 5, 2]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何对数组进行排序(索引)以使用这些索引将原始数组从最小到最大值排序 的相关文章

随机推荐