双调数组中的二分查找

     双调数组是指所有元素先递增后递减的数组,对其进行二分查找时,应先用二分查找找出数组中的最大项,再对左右两个单调子数组进行二分查找。代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
Item BitonicSearch(Item bitonicArray[],int length,int searchKey)
{
    if((bitonicArray == NULL) || (lenght <= 0))
    {
        return NULLItem;
    }
 
    int indexOfMaxItem = GetIndexOfMaxItem(bitonicArray,length);
 
    // 获取针对双调数组的递增部分的搜索结果
    Item result = BinarySearch(bitonicArray,0,indexOfMaxItem,searchKey);
 
    if(result == NULLItem)
    {
        // 获取针对双调数组的递减部分的搜索结果
        result = BinarySearch(bitonicArray,indexOfMaxItem + 1,length - 1,searchKey);
    }
 
    return result;
}
 
int GetIndexOfMaxItem(Item bitonicArray[],int length)
{
    int low = 0;
    int high = length - 1;
    int middle;
 
    while(low < high)
    {
        middle = (low + high) / 2;
 
        // 检查bitonicArray[middle + 1]是否处于双调数组的递增部分中
        if(bitonicArray[middle] < bitonicArray[middle + 1])
        {
            // 如果处于,则数组的最大项的索引必不小于middle + 1
            low = middle + 1;
        }
        else
        {
            // 如果不处于,则数组的最大项的索引必不大于middle
            high = middle;
        }
    }
 
    // 此时low = high
    return low;
}

  

posted @   姚来飞  阅读(637)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示