简体   繁体   English

订购随机产生的数字的向量

[英]Ordering a vector of randomly generated numbers

I´m trying to solve a question but i can´t find why my code is not working for this problem. 我正在尝试解决一个问题,但是我找不到为什么我的代码无法解决该问题。 I have generated a random vector of 100 elements and im trying to order them into another. 我生成了100个元素的随机向量,并尝试将它们排序为另一个。 Somehow, my new generated vector is filled with the last index value of the random vector. 不知何故,我新生成的向量填充了随机向量的最后一个索引值。

int[] vetorAleatory = new int[100];

for (int i = 0; i < vetorAleatory.length; i++) {
    vetorAleatory[i] = new Random().nextInt(1000);
}

int[] vetorByOrder = new int[100];
int newVetorPosition = 0;

for (int i = 0; i < 100; i++) {
    for (int x = 0; x < 100; x++) {

        vetorByOrder[newVetorPosition] = 2000;
        if (vetorAleatory[i] < vetorByOrder[newVetorPosition]) {
            boolean newEntry = true;
            for (int y = 0; y < newVetorPosition; y++) {
                if (vetorByOrder[y] == vetorByOrder[newVetorPosition]) {
                    newEntry = false;
                    break;
                }
            }
            if (newEntry == true) {
                vetorByOrder[newVetorPosition] = vetorAleatory[x];
            }
        }
        if (x == 99) {
            newVetorPosition++;
        }
    }
}

for (int i = 0;i<100;i++) {
    System.out.print(vetorAleatory[i] + ", " + vetorByOrder[i] + System.lineSeparator());
}

First you do not need 3 loops to sort an array. 首先,您不需要3个循环即可对数组进行排序。 You need only 2 and in case of quick search, it is even less than that. 您只需要2个,在快速搜索的情况下,它甚至更少。 You can check this example Array sort and search , or you can use built in Arrays.sort method in Java 您可以检查此示例Array sort and search ,也可以使用Java中内置的Arrays.sort方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM