1. 程式人生 > >Day2二分查詢

Day2二分查詢

書上的二分查詢是定義了一個有序陣列,然後二分查詢返回一個bool型別,我這裡寫的是隨便輸入一個數組,二分查詢,找到了返回位置,找不到輸出“找不到”

package bbb;
 
import java.util.Scanner;
 
public class Binary {
 
    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);
        int k = 1;
        System.out.println("輸入個數");
        int n = reader.nextInt();
        Stu[] s = new Stu[500];
        System.out.println("輸入值");
        for (int i = 0; i < n; i++) {
            s[i] = new Stu();
            s[i].v = reader.nextInt();
            s[i].t = k;
            k++;
        }
        //你這裡沒有輸入要查詢的數字
        System.out.println("輸入要查詢的數字");
        int m = reader.nextInt();
        //氣泡排序
        for (int i = 0; i < n - 1; i++) {
            for (int j = 0; j < n - i - 1; j++) {
                if (s[j].v > s[j + 1].v) {
                    swap(s[j], s[j + 1]);
                }
            }
        }
 
        if (binarySort(s,n,m) == -1) {
            System.out.println("找不到");
        } else {
            System.out.println("找到了,在第" + s[binarySort(s, n,m)].t + "個位置");
        }
    }
 
    public static void swap(Stu x, Stu y) {
        Stu temp;
        temp = x;
        x = y;
        y = temp;
    }
 
    public static int binarySort(Stu[] source,int n, int key) {
        int low = 0;
        int high =n - 1; //n為輸入的個數
        while (low <= high) {
            int mid = (low + high) / 2;
            int midVal = source[mid].v;
            if (midVal < key) {
                low = mid + 1;
            } else if (midVal > key) {
                high = mid;
            } else {
                return mid;
            }
        }
        return -1;
    }
 
}
 
class Stu {
    int v,t = 0;// v為值     t為位置
}

這個小演算法期間除了很多問題,非常感謝dota2吧的各位大哥照顧我這個小萌新,給我耐心解答哈哈~