二分查找大家都知道,但是二分查找第一次出现和最后出现不一定都会,仍然使用二分的思想,并且时间复杂度还是O(logn),与普通二分不同的是,在查找到匹配数字后,并不是马上返回,继续查找,直到最后只剩下一个数字,具体代码如下:
查找最后出现:
/*
* bi_search.cpp
*
* Created on: 2012-6-17
* Author: ict
*/
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
int bi_search(int *a, int l, int u, int t)
{
assert(l <= u);
int m;
while(l <= u)
{
m = (l + u) >> 1;
if((l + u)%2 == 1) //向上取整 ceil function
m++;
if(a[m] == t && l == u) //if there is only one element and equal the target
return m;
else
{
if(a[m] < t)
l = m + 1;
else
if(a[m] > t)
u = m - 1;
else
if(a[m] == t)
l = m; //修改左边数字
}
}
return -1;
}
int main()
{
int a[] = {1, 1, 1, 1, 1};
printf("%d\n", bi_search(a, 0, sizeof(a) / sizeof(int) -1, 1));
return 0;
}
查找第一次出现:
/*
* bi_search.cpp
*
* Created on: 2012-6-17
* Author: ict
*/
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
int bi_search(int *a, int l, int u, int t)
{
assert(l <= u);
int m;
while(l <= u)
{
m = (l + u) >> 1; //默认是向下取整
//if((l + u)%2 == 1) //向上取整 ceil function
//m++;
if(a[m] == t && l == u) //if there is only one element and equal the target
return m;
else
{
if(a[m] < t)
l = m + 1;
else
if(a[m] > t)
u = m - 1;
else
if(a[m] == t)
u = m; //修改左边数字
}
}
return -1;
}
int main()
{
int a[] = {1, 1, 1, 1, 1};
printf("%d\n", bi_search(a, 0, sizeof(a) / sizeof(int) -1, 1));
return 0;
}