qq_26964961
qq_26964961
采纳率100%
2017-07-31 05:03 阅读 1.2k
已采纳

java的二分法怎么写??

30

求一个简单的二分法,用Java实现,在线,等急用。谢谢。。。。。。。。。。。。。。。。。。。。。。。

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

3条回答 默认 最新

  • 已采纳
    cao_yanjie cao_yanjie 2017-07-31 05:07

    public class BinaryTest {
    public static int binary(int[] array,int value) {
    int low = 0;
    int high = array.length -1;
    while (low <= high){
    int mid = (low+high)/2;
    if (value == array[mid])
    return mid;
    if (value > array[mid])
    low = mid +1;
    if (value < array[mid])
    high = mid -1;

        }
        return -1;
    
    }
    
    public static void main(String[] args) {
        int[] a = {1,3,6,8,12,34,67,99};
        int value = binary(a,3);
        System.out.println(value);
    }
    

    }

    点赞 2 评论 复制链接分享
  • qq_34402394 小-鸟 2017-07-31 05:11

    public int binarySearch(int[] a,int num){
    int low = 0;
    int high = a.length - 1;

    while(low <= high){
    int middle = (low + high) / 2;
    if(num == a[middle])
    return middle;
    else if(num < a[middle])
    high = middle - 1;
    else
    low = middle + 1;
    }

    return -1;
    }

    点赞 1 评论 复制链接分享
  • u010637211 zyh127 2017-07-31 09:47

    int main()
    {
    int A[] = { 5, 2, 9, 4, 7, 6, 1, 3, 8 };// 从小到大二分插入排序
    int n = sizeof(A) / sizeof(int);
    int i, j, get, left, right, middle;

    for (i = 1; i < n; i++)                 
    {
        get = A[i];                         
        left = 0;                           
        right = i - 1;                      
        while (left <= right)              
        {
            middle = (left + right) / 2;
            if (A[middle] > get)
                right = middle - 1;
            else
                left = middle + 1;
        }
        for (j = i - 1; j >= left; j--)    
        {
            A[j + 1] = A[j];            
        }
        A[left] = get;                    
    }
    printf("二分插入排序结果:");
    for (i = 0; i < n; i++)
    {
        printf("%d ", A[i]);
    }
    printf("\n");
    return 0;
    

    }

    点赞 1 评论 复制链接分享

相关推荐