简体   繁体   中英

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. 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. You need only 2 and in case of quick search, it is even less than that. You can check this example Array sort and search , or you can use built in Arrays.sort method in Java

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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