这是我写的程序,不知道为什么最后打印出来是-1.明明在数组里面啊。郁闷public class ExamResult{
public static void BubbleSort(int b []){
int temp;
for(int i=0;i<b.length;i++) {
for(int j=0;j<b.length-1;j++) {
if(b[j]<b[j+1]) {
temp = b[j];
b[j] = b[j+1];
b[j+1] = temp;
}
}
}
for(int i=0;i<b.length;i++){
System.out.println("排序后的数组是"+b[i]+" ");
}
}
public static int BinarySearch(int a[],int key){
int low = 0;
int high = a.length-1;

while(low<=high){
int mid = (low+high)/2;
if(key==a[mid]){
System.out.println("找到了!!!");
return mid;
}
else if(key<a[mid]) {
high = mid-1;
}
else {
low = mid+1;
}
}
System.out.println("没有找到");
return -1;
}
public static void main(String[] args) {
int score[] = {568,487,635,598,521};
BubbleSort(score);
int key = 598;
int index = BinarySearch(score,598);
System.out.println("它的位置是score["+index+"]");
}
}

解决方案 »

  1.   

    public class ExamResult {
    public static void BubbleSort(int b[]) {
    int temp;
    for (int i = 0; i < b.length; i++) {
    for (int j = 0; j < b.length - 1; j++) {
    if (b[j] < b[j + 1]) {
    temp = b[j];
    b[j] = b[j + 1];
    b[j + 1] = temp;
    }
    }
    }
    for (int i = 0; i < b.length; i++) {
    System.out.println("排序后的数组是" + b[i] + " ");
    }
    } public static int BinarySearch(int a[], int key) {
    int low = 0;
    int high = a.length - 1; while (low <= high) {
    int mid = (low + high) / 2;
    if (key == a[mid]) {
    System.out.println("找到了!!!");
    return mid;
    } else if (key < a[mid]) {
    low = mid + 1;
    } else {
    high = mid - 1;
    }
    }
    System.out.println("没有找到");
    return -1;
    } public static void main(String[] args) {
    int score[] = { 568, 487, 635, 598, 521 };
    BubbleSort(score);
    int key = 598;
    int index = BinarySearch(score, 598);
    System.out.println("它的位置是score[" + index + "]");
    }
    }key < a[mid] 和  key > a[mid] 的执行语句交换下位置就行了
      

  2.   

    可以把冒泡排序改一下就好了,LZ的排序是降序的,而LZ二分查找是按数组是升序查找,自然找不到
    冒泡排序改进一点:
    1、可以只进行n-1趟就好了
    2、每次选一个相对最大的往后面放了,所以内层循环可以让j<b.length-1-i,因为后面的i个已经放好了
    改后如下:  public static void BubbleSort(int b []){
            int temp;
            for(int i=0;i<b.length-1;i++) {
                for(int j=0;j<b.length-1-i;j++) {
                    if(b[j]>b[j+1]) {
                    temp = b[j];
                    b[j] = b[j+1];
                    b[j+1] = temp;
                    }
                }
            }
            for(int i=0;i<b.length;i++){
                System.out.println("排序后的数组是"+b[i]+" ");
            }
        }