2006
12
11
23
08
用二元搜尋找upperbound和lowerbound.
記錄用. 用二元搜尋找upperbound和lowerbound.
例如:
0 1 2 3 4 5 6 7 8 9 10
----------------------------
0 0 1 1 1 2 2 2 2 3 3
要搜尋出從2~4都是1.
int findUpper1(int *pNum,int upperBound,int lowerBound,int n)
{
int middle;
if (pNum[upperBound]==n)
return upperBound;
while (upperBound + 1 < lowerBound) {
middle = (upperBound + lowerBound) / 2;
if (pNum[middle] < n) {
upperBound = middle ;
} else if (pNum[middle] > n) {
lowerBound = middle ;
} else if (pNum[middle] == n) {
lowerBound = middle;
}
}
if (pNum[lowerBound] == n)
return lowerBound;
return -1;
}
int findLower1(int *pNum,int upperBound,int lowerBound,int n)
{
int middle;
if (pNum[lowerBound]==n)
return lowerBound;
while (upperBound + 1 < lowerBound) {
middle = (upperBound + lowerBound) / 2;
if (pNum[middle] > n) {
lowerBound = middle ;
} else if (pNum[middle] == n) {
upperBound = middle;
} else {
upperBound = middle ;
}
}
if (pNum[upperBound] == n)
return upperBound;
return -1;
}
int findUpperLower1(int *pNum,int upperBound,int lowerBound,int n, int *u,int *l)
{
int lower=lowerBound;
int middle;
*u=*l=-1;
if (pNum[upperBound]==n) {
*u = upperBound;
} else {
while (upperBound + 1 < lowerBound) {
middle = (upperBound + lowerBound) / 2;
if (pNum[middle] < n) {
upperBound = middle ;
} else if (pNum[middle] > n) {
lower=lowerBound = middle ;
} else if (pNum[middle] == n) {
lowerBound = middle;
}
}
if (pNum[lowerBound] == n) {
*u = lowerBound;
} else {
return -1;
}
}
if (*u == -1)
return -1;
upperBound = *u;
lowerBound=lower;
if (pNum[lowerBound]==n) {
*l=lowerBound;
return 0;
}
while (upperBound + 1 < lowerBound) {
middle = (upperBound + lowerBound) / 2;
if (pNum[middle] > n) {
lowerBound = middle ;
} else if (pNum[middle] == n) {
upperBound = middle;
} else {
upperBound = middle ;
}
}
if (pNum[upperBound] == n) {
*l=upperBound;
return 0;
}
return -1;
}