在InsertInOrder中使用递归二进制搜索

时间:2014-02-27 20:37:23

标签: java recursion binary-search insertion-sort

我正在阅读未分类数字的文本文件

static void insertInOrder( int[] arr, int cnt, int newVal )
    {
        int belongs = -( bSearch( arr, 0, arr.length-1, newVal)) - 1;
        {
            for ( int i = cnt; i >= belongs+1 ; --i)
            {
                arr[i] = arr[i-1];
            }

        arr[belongs] = newVal;
    }

    }

    // We do not need to pass in count. The incoming lo and hi define the range
    public static int bSearch(int[] a, int lo, int hi, int key)
    {
    int mid = (lo+hi)/2;
    if(lo>hi)
        return -1;
    else if (a[mid]==key)
        return mid;
    else if (a[mid]<key)
        return bSearch(a, mid+1, hi, key);
    else
        return bSearch(a, lo, mid-1, key);
    }

二进制搜索正在运行,但我的insertinorder没有按升序排列数字,我无法弄清楚原因。它只是向后打印列表。这必须使用insertinorder中的递归二进制搜索来完成。

1 个答案:

答案 0 :(得分:0)

您是否已将最新代码复制到问题???中。

一个明显的问题是:

int belongs = -( bSearch( arr, 0, arr.length-1, newVal)) - 1;

方法 bSearch 在数组中找不到值时返回-1。当找不到newValue时,这将给出-2的插入点。您需要更改 bSearch 以返回找到的项目和位置。两个选项

  1. 创建(并返回)新类

    private class FoundResult {
        boolean found = true;
        int position;
    }
    
  2. 未找到时;返回-hi-1 即在bSearch中搜索一些东西:

    if(lo>hi)
       return -hi-1;
    

  3. 对于选项1,代码将大致(我没有测试过):

    static void insertInOrder( int[] arr, int cnt, int newVal )     {
    
        int belongs = bSearch( arr, 0, arr.length-1, newVal)).position ;
        for ( int i = cnt; i >= belongs+1 ; --i) {
           arr[i] = arr[i-1];
        }
    
        arr[belongs] = newVal;
    }
    
    // We do not need to pass in count. The incoming lo and hi define the range
    public static FoundResult bSearch(int[] a, int lo, int hi, int key)
    {
    int mid = (lo+hi)/2;
    FoundResult ret;
    if(lo>hi) {
        ret = new FoundResult();
        ret.found = false;
        ret.position = hi;
        return ret;
    } else if (a[mid]==key) {
        ret = new FoundResult();
        ret.position = hi;
        return ret;
    } else if (a[mid]<key) {
        return bSearch(a, mid+1, hi, key);
    } else {
        return bSearch(a, lo, mid-1, key);
    }
    

    对于选项2,代码大致为:

    static void insertInOrder( int[] arr, int cnt, int newVal )     {
    
        int belongs = bSearch( arr, 0, arr.length-1, newVal)) ;
        if (belongs < 0) {
            belongs  = -1 - belongs ;
        }
        for ( int i = cnt; i >= belongs+1 ; --i) {
           arr[i] = arr[i-1];
        }
    
        arr[belongs] = newVal;
    }
    
    // We do not need to pass in count. The incoming lo and hi define the range
    public static int bSearch(int[] a, int lo, int hi, int key)
    {
    int mid = (lo+hi)/2;
    FoundResult ret;
    if(lo>hi) {
        return - hi - 1;
    } else if (a[mid]==key) {
        return hi;
    } else if (a[mid]<key) {
        return bSearch(a, mid+1, hi, key);
    } else {
        return bSearch(a, lo, mid-1, key);
    }