Java:组合排序函数计算错误的结果



我有一个程序,可以生成6行数字(int数组)。 我正在将输出传递给另一个程序,该程序使用 BubbleSort 算法对其进行排序并将其写入文本文件。 如果使用第一个程序而不通过它工作正常,没有重复的数字没有零。但是在排序时有重复的数字,甚至我也见过零,零的情况我无法重现 ATM,而是重复出现的数字。它是否与多线程/并行处理或执行它的环境有关,它由 AMD 多核 win 10 主机和 deb jessie Guest 组成。

java LottoArray | java BubbleSort>test2.txt//终端

测试2.txt

2 13 16 20 27 40 
9 14 17 21 25 41 
6 11 11 19 27 44 
4 10 25 34 39 47 
11 12 17 36 44 48 
1 15 23 31 39 40 
3 22 22 23 33 45 
1 25 26 26 35 49 
11 14 24 25 41 49 
6 6 14 17 38 46 
4 19 19 28 35 39

如您所见,最后一行之前的行中的六是双倍,22s 和 11s。

public class LottoArray{
public static void main (String [] args){
for(int o=0;o<=10;o++){
int Reihe [] = new int [6];
int zahl;
int j=0;
int i= 0;
while(j<Reihe.length){
zahl = (int) (Math.random()*50);
boolean schonda = false;
while ( i<j){
if(Reihe[i]== zahl) 
schonda=true;
i++;
}
if(schonda==false && zahl !=0){
Reihe[j]=zahl;
j++;}
}
for(int z=0;z<6;z++){
System.out.print(Reihe[z]+" ");
}   
System.out.println();
}  
}
}
public class BubbleSort {
public static void main(String args[]) {
int arr[]= new int[6];
while(!StdIn.isEmpty()){
for(int i=0;i<6;i++)
arr[i]= StdIn.readInt();
boolean getauscht;
do {
getauscht= false;       

for (int i=0; i<arr.length-1; i++) {
if ( arr[i] > arr[i+1]) {
int tmp = arr[i];   
arr[i] = arr[i+1];
arr[i+1] = tmp;
getauscht = true;
}
}
}while(getauscht); 

for (int i=0; i<arr.length; i++)
System.out.print(arr[i]+" " );
System.out.println();
}
}
}

如果我使用没有 bubbleSort 的代码并将输出流式传输到文本文件中,则没有重复的数字和零,因为这应该是不可能的,因为我将条件编码if(schonda==false && zahl !=0)

15 2 20 5 26 34 
13 6 15 33 12 37 
44 17 16 23 40 25 
25 47 10 43 40 44 
25 29 3 30 10 41 
32 1 23 35 43 28 
9 34 28 32 33 25 
5 46 31 16 25 9 
9 13 16 18 40 5 
29 15 16 2 16 15 
34 33 44 13 43 48

有没有人经历过这种不应该发生的数字?

你的问题出在这个乐透数组块中:

int j=0;
int i= 0;
while(j<Reihe.length){
zahl = (int) (Math.random()*50);
boolean schonda = false;
while ( i<j){
if(Reihe[i]== zahl) 
schonda=true;
i++;
}
if(schonda==false && zahl !=0){
Reihe[j]=zahl;
j++;
}
}
  • 第一次从上面进入while (i<j){循环时(对于第一个元素),i 和 j 都是 0,因此不会执行循环。
  • 第二次(检查第二个数字),i为 0,j为 1,因此执行循环并增加i
  • 第三次(检查第三个数字),i是 1,j是 2。
  • 其余的都一样,i总是j-1.

这是一个错误,因为您没有开始检查第一个元素。我想你只是因为运气而使用BubbleSort得到重复项,因为错误不存在。

要解决此问题,请在第一个while内初始化i,在与schondavar 相同的位置,而不是在上面使用j

最新更新