BinarySearch(二分查找)

2016.7.22

对rank()函数进行了修改:

private static int rank(int key, int[] whitelist) {

    int low = 0;
    int high = whitelist.length - 1;
    while(low <= high) {
        int mid = low + (high - low) / 2;
        if(key < whitelist[mid]) {
            high = mid - 1;
        } else if(key > whitelist[mid]) {
            low = mid + 1;
        } else {
            return mid;
        }
    }
    return -1;
}

这样就不用在main函数里使用has标签和for循环去判断key值是否在数组里面


2016.7.21

import java.util.Arrays;
import java.util.Scanner;

/**
 * Created by ZYQ on 2016/7/21.
 */
public class BinarySearch {

    // 二分查找的方法
    private static int rank(int key, int[] whitelist) {

        int low = 0;
        int high = whitelist.length - 1;
        while(low <= high) {
            int mid = (low + high) / 2;
            if(key < whitelist[mid]) {
                high = mid;
            } else if(key > whitelist[mid]) {
                low = mid;
            } else {
                return mid;
            }
        }
        return -1;
    }

    public static void main(String[] args) {

        int[] whileList=new int[10];
        // 输入数组中的数
        System.out.println("Enter the numbers:");
        for(int i = 0; i < 10; i++) {
            Scanner s = new Scanner(System.in);
            whileList[i] = s.nextInt();
        }
        // 二分查找的前提是排好序
        Arrays.sort(whileList);
        System.out.println("Your arrays is:");
        // jdk1.5推出的foreach语法
        for (int i : whiteList) {
            System.out.print(i + "  ");
        }
        System.out.println();
        // 输入要查找的数
        System.out.println("Enter your find numbers:");
        Scanner scanner = new Scanner(System.in);
        while(scanner.hasNextInt()){
            int key = scanner.nextInt();
            int has = 0;
            for (int i = 0; i < whileList.length; i++) {
                if(key == whileList[i]) {
                    has = 1;
                }
            }
            if (has == 1) {
                int result = rank(key, whileList);
                System.out.println(key + " is in the position of " + (result + 1));
            } else {
                System.out.println(key+" is not in the array!");
            }
        }
    }

}

今天开始学习数据结构与算法,写的第一个算法,感觉这个我写的这个代码效率不够高,等学一段时间后再改进!

你可能感兴趣的:(Java,Algorithms)