gpt4 book ai didi

java - 对随机生成的数字 vector 进行排序

转载 作者:行者123 更新时间:2023-12-02 03:43:41 25 4
gpt4 key购买 nike

我正在尝试解决一个问题,但我找不到为什么我的代码不能解决这个问题。我生成了一个包含 100 个元素的随机 vector ,并尝试将它们排序到另一个 vector 中。不知何故,我新生成的 vector 填充了随机 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());
}

最佳答案

首先,您不需要 3 个循环来对数组进行排序。您只需要 2 个,如果快速搜索,甚至还更少。你可以查看这个例子Array sort and search ,或者您可以使用Java中内置的Arrays.sort方法

关于java - 对随机生成的数字 vector 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56821432/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com