常用算法(1)

来源:互联网 发布:过滤器 angular在js 编辑:程序博客网 时间:2024/05/16 18:23

求公约数:

#include <iostream>#include <stdlib.h>using namespace std;int main(int argc, char* argv[]){  int a = atoi(argv[1]);  int b = atoi(argv[2]);  while(a != b){    if(a>b)      a -= b;    else      b -= a;  }  cout<<"answer:"<<a<<endl;  return 0;}

字符串左旋转问题:

(1)利用两次求逆的方法

(2)利用循环替换的方法(比较少见,所以下面以此为基础的代码)

设有len长度的字符串,左旋转i个。

str[x] = str[(x+i)%len]

x = (x+i)%len;

#include <iostream>#include <stdlib.h>#include <string.h>using namespace std;void rotate_str(char*, int);/* * Usage: ./rotate_str string int * string : the string you want to rotate * int : the rotate number */int main(int argc, char* argv[]){  char* str = argv[1];  int i = atoi(argv[2]);  cout<<"origin:\t"<<str<<endl;  rotate_str(str, i);  cout<<"rotate:\t"<<str<<endl;  return 0;}void rotate_str(char* str, int i){  int len = strlen(str);  int index = 0;  char temp = str[0];  while((index+i)%len != 0){    str[index] = str[(index+i)%len];    index = (index+i)%len;  }  str[index] = temp;}

(3)利用位图实现排序

例如给定1,000,000个数字,数字大小是[0,10,000,000),假设没有重复,采用位图排序

《1》首先利用rand() srand((unsigned int)time(0)) 生成随机数的方法创建1,000,000个随机数,范围限制在10,000,000

由于要求数据不能重复,所以这里我们利用交换的方法,每次随机产生的数下标。

我们定义了范围的随机产生器: #define rand_range(a,b) rand()%(b-a)+a产生[a,b)之间的随机数

这里数组x一定要用堆上建立,否则栈上空间不足会产生错误。最后记得delete

#include <stdlib.h>#include <iostream>#include <time.h>#define random(x) rand()%x#define rand_range(a,b) rand()%(b-a)+a using namespace std;/* * argv[0] : program name * argv[1] : scope * argv[2] : the number */int main(int argc, char* argv[]){    if(argc<3){    cerr<<"error args\n";    return -1;  }  int scope = atoi(argv[1]);  int num = atoi(argv[2]);  srand((unsigned int)time(0));  //   int* x = new int[scope];  for(int i=0; i<scope; i++)    x[i] = i;  // shuffle  for(int i=0; i<num; i++){    int idx = rand_range(i, scope);    int temp = x[i];    x[i] = x[idx];    x[idx] = temp;    cout<<x[i]<<endl;  }  delete[] x;  return 0;}

Linux控制台下执行

./gen_rand_num 10000000 1000000 > rand_num.dat

《2》排序,利用位图

利用c++ 自带的bitset

#include <iostream>#include <bitset>#include <stdlib.h>/* * argv[1] : scope */using namespace std;int main(int argc, char* argv[]){  const int num = 10000000;  bitset<num> bs;  int digit;  while(cin>>digit){    bs.set(digit);  }  // optput  for(int i=0; i<num; i++){    if(bs.test(i))      cout<<i<<endl;  }  return 0;}

$ time ./sort_num < rand_num.dat > sort_result.dat 
real    0m1.514s
user    0m0.623s
sys    0m0.816s


我们直接利用shell 自带的sort 排序

time sort -n rand_num.dat > sort_result2.dat

real    0m1.742s
user    0m1.702s
sys    0m0.007s

看到,其实还是sort系统时间少

0 0
原创粉丝点击