作者jeonjh (小鲔鱼)
站内java
标题Re: [问题] bubble sort
时间Sat Apr 26 12:10:17 2008
※ 引述《gkofay (放空~我想休学= =)》之铭言:
: public static void sort(int num[])
: {
: int temp;
: for(int j=0;j<num.length;j++)
: {
: if(num[j]<num[j+1])
: {
: temp=num[j];
: num[j]=num[j+1];
: num[j+1]=temp;
: }
: }
: }
想像一下输入1 3 2 4!
length是4!
if( num[j] < num[j+1] )这一行就会错了...
跑到j = 3 (j < length 4) 的时後,j+1是4!
但你的array总共有0~3(length 4)
而你用num[4]就retrive就丢出array index out of bounds的exception
: 问题(1)为什麽我run的时候到了sort函数会出现
: exception in thread "main" java.lang.ArrayIndexOut Of BoundsException:6
: at h42201.sort(h42201.java:37)
: at h42201.main(h42201.java:19)
: 我觉得是这行开始出问题~if(num[j]<num[j+1])
: 可是我不懂@@哪里错ㄌ~我之前学c++可以这样用耶@@在java有什麽不同吗
: 还是只是纯粹我自己写错= =
: 问题(2)他要求输入正整数,关於正整数的设定如了用if之外
: 有没有特殊的指令可以限定,因为用if的话~好像会写出一长串= =
: 问题(3)java有没有像是标签这种功能呢?
: 比如说
: being: <---我在这里标签名称为begin
: xxxxxxxxxx
: xxxxxxxxxxx
: xxxxxxxxxxx
: (xxx是程式内容)
: ?????<-----那如果我要重後面的某一行跳回begin的标签,指令要怎麽写?
: 不知道java是否有这个功能,我记得c++有
没有,这不符oo的精神。
: 内容有点长!希望各位大大可以耐心指教~~感温
最後,你这不像bubble sort啊?还是我对bubble sort认知有错误?
什麽sort我都看不出来!如果是bubble sort应该还少了一层回圈
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 118.169.25.240
1F:推 LawlietDo:他的bubble 是 O(n) 版 比 quick sort 还快呢XD 04/26 12:20
2F:推 lookyya:O(n) ... 可以写paper了... XD 04/26 14:54