1. 最大子序列和问题
1 int MaxSubsquenceSum(const int A[],int N){ 2 3 int ThisSum,MaxSum,j; 4 5 ThisSum = MaxSum = 0; 6 7 for(j=0;j<N;j++){ 8 9 ThisSum += A[j]; 10 11 if(ThisSum > MaxSum) 12 13 MaxSum = ThisSum; 14 15 else if(ThisSum < 0) 16 17 ThisSum = 0; 18 19 } 20 21 return MaxSum; 22 23 }
2. 二分查找法
1 int BinarySearch(const ElementType A[], ElementType X, int N){ 2 3 int Low,Mid,High; 4 5 Low=0;High=N-1; 6 7 while(Low <= High){ 8 9 Mid = (Low + High)/2; 10 11 if(a[Mid] < X) 12 13 Low = Mid + 1; 14 15 else if(a[Mid] > X) 16 17 High = Mid -1; 18 19 else 20 21 return Mid; 22 23 } 24 25 return NotFound; 26 27 }
3.欧几里德算法(求最大公因数)
1 unsigned int Gcd(unsigned int M,unsigned int N){ 2 3 unsigned int Rem; 4 5 while(N > 0){ 6 7 Rem = M % N; 8 9 M = N; 10 11 N = Rem; 12 13 } 14 15 return M; 16 17 }
4.幂运算(计算X的n次方)
1 long int Pow(long int X,unsigned int N){ 2 3 if(N == 0) return 1; 4 5 if(N == 1) return X; 6 7 if(IsEven(N)) return Pow(X * X,N/2); 8 9 else return Pow(X * X,N/2) * X; 10 11 }