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

java的二分法怎么写??

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

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • 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);
    }
    

    }

    已采纳该答案
    打赏 评论
  • 小-鸟 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;
    }

    打赏 评论
  • 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;
    

    }

    打赏 评论

相关推荐 更多相似问题