你只要会下结果就知道是多会的古怪了。
下面是每个循环的结果:
1:
the flag si:0
move top
2:
the flag si:1
move top
3:
the flag si:2
move top
就在第4次有问题了后面的结果是:
move buttom
the flag si:3
move top
明显是多了个move buttomd 在前面。
下面是每个循环的结果:
1:
the flag si:0
move top
2:
the flag si:1
move top
3:
the flag si:2
move top
就在第4次有问题了后面的结果是:
move buttom
the flag si:3
move top
明显是多了个move buttomd 在前面。
int flag = 0;
int mid = 0;
do{
mid = (int)((toppoint+buttompoint)/2);
System.out.println("the flag si:"+flag++);
if (parameter == array[mid]){
result = array[mid];
System.out.println("give result");
}
if (parameter < array[mid]){
toppoint = mid;
System.out.println("move top");
}
if (parameter > array[mid]){
buttompoint = mid;
System.out.println("move buttom");
}
}while ((toppoint > buttompoint)&&
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
(parameter != array[mid]));
~~~~~~~~~~~~~~~~~~~~~~~~~~
}
move top
the flag si:1
move top
the flag si:2
move top
the flag si:3
move buttom
the flag si:4
move top
the flag si:5
move buttom
the flag si:6
give result
result is :9
Press any key to continue...
这样的结果满意了吧。风格不好。((int)(toppoint+buttompoint)/2)干吗不
用一个变量代替,so long
static int array[] = new int[120];
static int result;
static int toppoint = 100;
static int buttompoint = 1;
public static void main(String args[]) {
System.out.println("Program start...");
initarray();
findnote(2);
System.out.println("result is :"+result);
}
public static void initarray(){
for(int i=1;i<=100;i++){
array[i] = i;
}
}
public static void findnote(int parameter ){
int flag = 0;
do{
System.out.println("--------------------------");
System.out.println("the flag si:"+flag++);
if (parameter == array[(int)((toppoint+buttompoint)/2)]){
result = array[(int)((toppoint+buttompoint)/2)];
System.out.println("give result...");
break;
}
else if (parameter < array[(int)((toppoint+buttompoint)/2)]){
toppoint = ((int)(toppoint+buttompoint)/2);
System.out.println("move top...");
}
else{
buttompoint = ((int)(toppoint+buttompoint)/2);
System.out.println("move buttom...");
}
}while (toppoint != buttompoint);
}
}