1.1一次友好的对话

来源:互联网 发布:广西广电网络多少钱 编辑:程序博客网 时间:2024/05/16 07:01

习题:

3.系统排序:在命令行中由操作系统进行排序

5.有限内存空间,无法存放完整位图,若采用多趟排序的方式,k趟,则需要先在n个数中找到前 n/k 个数,耗费时间为n,读入内存进行排序,输出到文件中,之后,再次读入前 2 n/k个数,进行排序,输出到接着的文件中,共需要kn时间.

补充(real time 是wall clock time, 从开始到结束elapsed 的时间;

           user time是 cpu 才user-mode下,运行的总时间;

           sys time 是cpu 在kernel中的时间;

          user+sys是cpu的运行总时间,若是有多线程,则将超过wall clock time ,因为需要添加上thread的运行时间

        
上述的real时间包括子进程的时间, 而sys的时间例如花费在malloc上,fread上,fwrite上等等,这些都是kernel functions)


1.位图排序

#include <stdio.h>#define BITSPERWORD 32#define SHIFT 5#define MASK 0x1F#define N 10000000int a[1+N/BITSPERWORD];//if N%BITSPERWORD is not 0, we still need more bits to represent the left numbersvoid set(int i) {a[i>>SHIFT] |= (1 << (i & MASK));}//We find the position of the int we will setvoid clc(int i) {a[i>>SHIFT] &= ~(1 << (i & MASK));}//i & MASK means we need to use it to know how many bits we need to move for 1int test(int i) {return a[i>>SHIFT] & (1 << (i & MASK));}// if i is larger we set its bits into 0, but we have already use them  //in when shift to find the int positionint main(){int i;for (i = 0; i < N; i++)clc(i);FILE *f = fopen("r.txt", "r");while (fscanf(f, "%d", &i) != EOF){set(i);}for (int i = 0; i < N; i++)if (test(i))printf("%d\n", i);return 0;}

c++/STL

#include <iostream>#include <fstream>#include <set>#include <string>using namespace std;int main(void){set<int> s;int a[10];int i = 0;ifstream myfile;myfile.open("r.txt");while (myfile >> a[i]){s.insert(a[i]);i++;}set<int>::iterator j;for (j = s.begin(); j != s.end(); j++)cout << *j << endl;}


c/libary qsort
#include <stdio.h>#include <stdlib.h>int compare(int *a, int *b){return *a - *b;}int main(){int i = 0;int a[10];FILE *f = fopen("r.txt", "r");while (fscanf(f, "%d", &a[i]) != EOF)i++;qsort(a, 10, sizeof(int), compare);for (int i = 0; i < 10; i++)printf("%d\n", a[i]);}

4
#include <stdio.h>#include <time.h>#include <stdlib.h>#define N 1000#define k 500int main(){int i = 0;int a[N];srand(time(NULL));clock_t b = clock();for (i; i < N; i++)a[i] = i;for (i = 0;i < k; i++){int tmp = a[i];int t = i + (rand() % (int)(N - i + 1));a[i] = a[t];a[t] = tmp;}for (i = 0;i < k; i++)printf("%d\n", a[i]);clock_t e = clock();double u = (double)(e-b);printf("time is %f\n", u);}

数组元素的交换,保证后面的元素都不会与之前已有的元素相同

6.若有重复的元素,则用10 000 000个半字节元素的数组来存储,数组元素的下标就表示出现的元素,此时并不是位图模式,而是数组模式,但是若是没有重复的时候就采用数组模式,则无法利用数组下标的功能


发现:数组其实可以用作类似map,数组元素的下标可以看作key,数组元素对应的值可以看作value

           由10.看出,二维数组可以看作开放散列,其中,行号可以看作是散列值,而每一行则可以看作是将独立链法换做数组




     


0 0
原创粉丝点击