簡體   English   中英

訂購隨機產生的數字的向量

[英]Ordering a vector of randomly generated numbers

我正在嘗試解決一個問題,但是我找不到為什么我的代碼無法解決該問題。 我生成了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());
}

首先,您不需要3個循環即可對數組進行排序。 您只需要2個,在快速搜索的情況下,它甚至更少。 您可以檢查此示例Array sort and search ,也可以使用Java中內置的Arrays.sort方法

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM