[英]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.