关于JAVA冒泡排序法,执行错误

l964772215 2015-08-19 09:00:36
public class jisuan{
public static void main(String[] args){
int[] num ={32,15,13,11,68,54,65};
int temp = 0;
for(int i = 0;i <= num.length-1;i++){

for (int j = 0;j <= num.length-1-i;j++){
if(num[j]>num[j+1]){
temp = num[j];
num[j] = num[j+1];
num[j+1] = temp;
}
}
}

for(int i = 0;i<num.length;i++){
System.out.print(num[i]+",");
}
System.out.println();
}
}
...全文
130 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
ITjavaman 2015-08-19
  • 打赏
  • 举报
回复
引用 6 楼 l964772215 的回复:
什么叫下标越界,就这道题解释一下
就比如 int [] sz ={1,2,3,4}; 数组sz的长度为4,下标为0~3,即sz[0]=1,0就是sz数组第一个元素的下标,你如果弄个sz[4]超出了最大下标,就叫数组越界 就上面这到题,当你i=0 j=5的时候 if(num[5]>num[6]) 中 num[6]越界
l964772215 2015-08-19
  • 打赏
  • 举报
回复
什么叫下标越界,就这道题解释一下
ITjavaman 2015-08-19
  • 打赏
  • 举报
回复
int [] num= {32,15,13,11,68,54,65}; for(int j= 0;j<num.length-1;j++){ int x=num[j]; int count=j; for(int i=j+1; i<sz.length; i++){ if(x>=sz[i]){ count = i; x=num[i]; } } if(count!=j){ changevule(count, j, num); } } static int[] changevule(int a,int b,int [] sz){ int c=sz[a]; sz[a]=sz[b]; sz[b]=c; return sz; } 个人写的笨方法
qq_27350687 2015-08-19
  • 打赏
  • 举报
回复
//冒泡排序 public static void bubbleSort(int [] arr) { for(int x=0;x<arr.length-1;x++) { for(int y=0;y<arr.length-x-1;y++) //-x:让每一次比较的元素减少, -1:避免角标越界 { if(arr[y]>arr[y+1]) {/* int temp=arr[y]; arr[y]=arr[y+1]; arr[y+1]=temp; */ swap(arr,y,y+1); } } } }
andre374 2015-08-19
  • 打赏
  • 举报
回复
擦,没注意,写错了 for (int i = 0; i < num.length - 1; i++) { for (int j = 0; j < num.length -i - 1; j++) { if (num[j] > num[j + 1]) { int temp; temp = num[j]; num[j] = num[j + 1]; num[j + 1] = temp; } } }
andre374 2015-08-19
  • 打赏
  • 举报
回复
数组越界

for (int i = 0; i < num.length - 1; i++) {

			for (int j = i+ 1; j < num.length - 1; j++) {
				if (num[j] > num[j + 1]) {
					int temp;
					temp = num[j];
					num[j] = num[j + 1];
					num[j + 1] = temp;
				}
			}
		}
豫让_______ 2015-08-19
  • 打赏
  • 举报
回复
for (int j = 0;j <= num.length-1-i;j++) i=0的时候,会下标越界, 把等于号去掉或者改成-2

50,542

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧