对分查找
给定一个整数X和整数A0,A1,…,AN-1,后者已经预先排序并存在内存中,求使得Ai=X的下标i,如果X不在数据中,则返回i=-1。
int BinarySearch (const ElementType A[], ElementType x, int N)
{
int Low, Mid, High;
Low = 0; High = N - 1;
while (Low <= High)
{
Mid = (Low + High) / 2;
if (A[Mid] < x)
Low = Mid + 1;
else if (A[Mid] > x)
High = Mid - 1;
else
return Mid; //Found
}
return NotFound //NotFound is defined as -1
}
欧几里得算法
计算两个整数的最大公因数(Gcd),通过连续计算余数直到余数是0为止,最后的非零余数就是最大公因数。
unsigned int Gcd (unsigned int M, unsigned int N)
{
unsigned int Rem;
while (N > 0)
{
Rem = M % N;
M = N;
N = Rem;
}
return M;
}
幂运算
递归算X^N
long int Pow (long int X;unsigned int N)
{
if (N == 0)
return 1;
if (IsEven(N))
return Pow (X * X, N / 2);
else
return Pow (X * X, N / 2) * X;
}