无序数组的“折半查找”

华为有道笔试题:

已知:无序数组,折半查找,各元素值唯一。 
函数原型是:
int Binary_Seach(int array[], int iValue, int iCount);
array是数组,在里面用折半查找的方法找等于iValue的值,找到返回1否则0,iCount是元素个数。

改了下返回结果     但思想是一样的   对无序数组来进行折半查找     这题2B了  

大概思想就是边快排边查找   这里的折半 我觉得应该理解成  二分法     (二分法&&最佳分界条件很重要)

/**
 * Created by albert.bai on 2014/11/10.
 */
public class Binary_Search {
    public static void Binary_Search(int array[], int value, int count) {
        int first = 0;
        int end = count - 1;
        int index = binarySearch(array, value, first, end);
        System.out.println(index);

    }

    public static int Partion(int a[], int first, int end) {
        int i = first;
        int j = end;
        while (i < j) {
            while (i < j && a[i] <= a[j]) {
                j--;
            }
            if (i < j) {
                int tem = a[i];
                a[i] = a[j];
                a[j] = tem;
                i++;
            }
            while (i < j && a[i] <= a[j]) {
                i++;
            }
            if (i < j) {
                int tem = a[i];
                a[i] = a[j];
                a[j] = tem;
                j--;
            }

        }
        return i;

    }

    public static int binarySearch(int array[], int value, int first, int end) {
        int index = -1;
        if (first <= end) {
            int mid = (first + end) / 2;
            int partion = Partion(array, first, end);
            if (array[partion] < value) {
                index = binarySearch(array, value, partion + 1, end);
            } else if (array[partion] > value) {
                index = binarySearch(array, value, 0, partion - 1);
            } else if (array[partion] == value) {
                index = array[partion];
            }
        }

        return index;
    }

    public static void main(String[] args) {
        int[] array = {5, 2, 4, 6, 1, 8, 0, 3};
        Binary_Search(array, 10, 8);
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值