我一直试图在java中对数组进行冒泡一段时间,但每次只做几次然后它跟随数组列表。
public void mysort() {
Random randomNumbers = new Random();
int randomArray[] = new int[20];
for (int j = 0; j <= 19; j++) {
randomArray[j] = randomNumbers.nextInt(200 + 1);
for (int k = 1; k < 20; k++) {
if (randomArray[k - 1] < randomArray[k]) {
int hjelp = randomArray[k - 1];
randomArray[k - 1] = randomArray[k];
randomArray[k] = hjelp;
}
}
}
for (int i = 0; i <= 19; i++) {
System.out.println(randomArray[i]);
}
}
如何让我的冒泡排序正常工作?
答案 0 :(得分:1)
您需要先填充数组。 您正在尝试同时填充和排序。
填充:
for (int j = 0; j <= 19; j++ ){
randomArray[j] = randomNumbers.nextInt(200+1);
}
排序:
BubleSort();
答案 1 :(得分:1)
您的代码应该是这样的:
Random randomNumbers = new Random();
int randomArray[] = new int[20];
for (int j = 0; j <= 19; j++) {
randomArray[j] = randomNumbers.nextInt(200 + 1);
}
for(int j=0;j<20;j++) {
for (int k = 1; k < 20; k++) {
if (randomArray[k - 1] < randomArray[k]) {
int hjelp = randomArray[k - 1];
randomArray[k - 1] = randomArray[k];
randomArray[k] = hjelp;
}
}
}
for (int i = 0; i <= 19; i++) {
System.out.println(randomArray[i]);
}
请注意,您是按降序执行此操作。如果你想按升序改变
if (randomArray[k - 1] < randomArray[k])
到
if (randomArray[k - 1] > randomArray[k])
答案 2 :(得分:1)
您应首先填充数组,然后调用排序。你正在对阵列进行“排序”20次,但它仍然不完整。
public void mysort() {
Random randomNumbers = new Random();
int randomArray[] = new int[20];
for (int j = 0; j < randomArray.length; j++) {
randomArray[j] = randomNumbers.nextInt(200) + 1;
}
for (int i = 0; i < randomArray.length; i++) {
for (int k = 1; k < randomArray.length; k++) {
if (randomArray[k - 1] < randomArray[k]) {
int hjelp = randomArray[k - 1];
randomArray[k - 1] = randomArray[k];
randomArray[k] = hjelp;
}
}
}
for (int i = 0; i < randomArray.length; i++) {
System.out.println(randomArray[i]);
}
}