public class BubbleSort{
public static void main (Stringargs[ ]){
int i,j;
int intArray[ ] ={30,1,-9,70,25};
int l=intArray .length;
for(i=1;i<l;i++)
for(j=0;j<l-i-1;j+ +)
if(intArray[j]>intArray[j+1]){
int t =intArray[i];
intArray[j]=intArray[j+1];
intArray[j+1]=t;
}
for(i=0;i<1;i++)
System.out.println(intArray[i]+″″);
}
}
这个冒泡排序可以运行但是结果不对,哪里错了啊?
public class BubbleSort{
public static void main (Stringargs[ ]){
int i,j;
int intArray[ ] ={30,1,-9,70,25};
int l=intArray .length;
for(i=1;iintArray[j+1]){
int t =intArray[i];
intArray[j]=intArray[j+1];
intArray[j+1]=t;
}
for(i=0;i<1;i++)
System.out.println(intArray[i]+″″);
}
}
这个冒泡排序可以运行但是结果不对,哪里错了啊?
第六行应该是 for(i=0;i<l-1;i++)
第六行应该是 int t =intArray[j];
为什么要用双重循环?
追答i代表次数
j代表比较位置
intArray i j j+1 ary[j] ary[j+1] [j]>[j+1] [j][j+1]
{8,2,3,7,1} 0 0 1 8 2 true 82
{2,8,3,7,1} 0 1 2 8 3 true 83
{2,3,8,7,1} 0 2 3 8 7 true 87
{2,3,7,8,1} 0 3 4 8 1 true 81
{2,3,7,1|8} 1 0 1 2 3 false
{2,3,7,1|8} 1 1 2 3 7 false
{2,3,7,1|8} 1 2 3 7 1 true 71
{2,3,1|7,8} 2 0 1 2 3 false
{2,3,1|7,8} 2 1 2 3 1 true 31
{2,1|3,7,8} 3 0 1 2 1 true 21
{1,2,3,7,8}
i = 0~ [j+1]){
[j][j+1]
}
看看这个应该会明白了
public class BubbleSort{
public static void main (Stringargs[ ]){
int i,j;
int intArray[ ] ={30,1,-9,70,25};
int l=intArray .length;
for(i=1;iintArray[j+1]){
int t =intArray[i];
intArray[j]=intArray[j+1];
intArray[j+1]=t;
}
for(i=0;i<1;i++)
System.out.println(intArray[i]+″″);
}
}
这个冒泡排序可以运行但是结果不对,哪里错了啊?
第一,让外边的循环i从0开始
第二,int i= intArray【j】 而不是i
为什么要用双重循环?