简单算法程序-C和C++
快速幂算法C++:用于以 log(n) 的复杂度求幂 $x^n$。
#include<iostream> using namespace std; long long fast_power(long long a, long long b){ long long ans = 1; while(b){ if (b&1)ans*=a; b >>= 1; a *= a; } return ans; } int main(){ long long n=5, m=10; cout<<fast_power(n, m)<<endl; return 0; }
快速幂余算法C语言:用于以 log(n) 的复杂度求 $x^n mod c$,以免先求幂在取余导致数值过大而产生数值溢出错误。
#include<stdio.h> int fast_power_mode(int a, int b, int c){ int ans = 1; a = a % c; while(b>0){ if (b&1){ ans=(ans*a)%c; }; b >>= 1; a = (a * a) % c; } return ans; } int main(){ int n=5, m=10, k=7; printf("%d\n", fast_power_mode(n, m, k)); return 0; }
快速排序算法C语言:用于以 nlog(n) 的时间复杂求对一个线性表排序。
#include<stdio.h> void fastsort(int* numbers, int begin, int end){ // int num_len = end - begin + 1; int num_len = sizeof(numbers); printf("sort array from index %d to %d, len: %d\n", begin, end, num_len); for(int i=0; i<num_len; i++) printf("%d, ", numbers[i]); printf("\n"); // printf("the length of array \"numbers\": %d\n", num_len); if(begin >= 0 && begin < num_len && end >= 0 && end < num_len && begin < end){ int i = begin, j = end; int vot = numbers[i]; while (i != j){ while(i<j && numbers[j]>=vot)j--; if(i<j) numbers[i++] = numbers[j]; while(i<j && numbers[i]<=vot)i++; if(i<j) numbers[j--] = numbers[i]; } numbers[i] = vot; fastsort(numbers, begin, j-1); fastsort(numbers,i+1, end); } } void fastsort_default(int* numbers){ // why? line 1 return 2 but line 2 return 8 // int num_len = sizeof(numbers) / sizeof(numbers[0]); // line 1 int num_len = sizeof(numbers); // line 2 printf("the length of array \"numbers\": %d\n", num_len); fastsort(numbers, 0, num_len-1); for(int i=0; i<num_len; i++) printf("%d, ", numbers[i]); printf("\n"); } int main(){ int numbers[] = {10, 7, 2, 4, 3, 8 ,9 ,19}; // int num_len1 = sizeof(numbers) / sizeof(numbers[0]); // int num_len2 = sizeof(numbers); // printf("%d, %d\n", num_len1, num_len2); fastsort_default(numbers); // C language need not to free a static array, but dynamic array. // delete []numbers; return 0; }
附编译执行的代码:
set filename=fastsortarray set postfix1=.c set postfix2=.exe gcc -g %filename%%postfix1% -o %filename%%postfix2% %filename%%postfix2%