对随机生成的数字的向量进行排序

我试图解决一个问题,但我找不到为什么我的代码不能解决这个问题。我生成了一个包含 100 个元素的随机向量,我试图将它们排列成另一个。不知何故,我新生成的向量充满了随机向量的最后一个索引值。


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());

}


泛舟湖上清波郎朗
浏览 124回答 1
1回答

白猪掌柜的

首先,您不需要 3 个循环来对数组进行排序。您只需要 2 个,在快速搜索的情况下,它甚至更少。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java