• 几个经典的小算法


    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 }
  • 相关阅读:
    Mac上安装Git
    原型对象和原型链
    ES6入门
    一边宽度固定,一边宽度自适应
    15种css居中方式
    阿里CDN核心技术解密
    尽量用const,enum,inline代替define
    Nginx安装
    百度笔试题:malloc/free与new/delete的区别(转)
    C++内存管理(转)
  • 原文地址:https://www.cnblogs.com/jiangjh/p/3076318.html
Copyright © 2020-2023  润新知