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!");
            }
        }
    }

}

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值