用户注册



邮箱:

密码:

用户登录


邮箱:

密码:
记住登录一个月忘记密码?

发表随想


还能输入:200字
云代码 - c代码库

插入排序

2017-12-18 作者: 柯侧耳倾听者举报

[c]代码库

#include <math.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#define NOT_FOUND -1
 
int get_rand(int upbound) {
    //srand(time(0)); //srand=stdlib.h; time=time.h
    return (int)(ceil(rand()%upbound)); //ceil=math.h; rand=stdlib.h
}
 
int get_runtime() {
    return clock(); //time=time.h
}
 
int linear_search(int arr[], int len, int key) { //continuing finding
    int j=-1; int i;
    for (i=0;i<=len-1;i++) if (arr[i]==key) j=i;
    return j;
}
 
 
int better_search(int arr[], int len, int key) { //terminating after finding
    int i;
    for (i=len-1;i>=0;i--) if (arr[i]==key) break;
    return i;
}
 
int sentinel_linear_search(int arr[], int len, int key) { //preventing violation
    int last;
    last=arr[len-1];
    arr[len-1]=key;
 
    int i=0;
    while (arr[i]!=key) i++;
    if (i<(len-1)) return i;
    if (last==key) return len-1;
    else return -1; //check whether is it just the last
}

int main() {
	srand(time(0));
	int a[200000];
	for (int k=0;k<=190000;k++) {
		a[k+10]=get_rand(10);
		if (k==131072) a[k+10]=22;
	}
	printf("1. get random numbers\n");
	for (int randi=0;randi<=10;randi++) 
		printf("%d\n",get_rand(100));
	printf("2. LINEAR_SEARCH\n");
	int time1_S=clock();
	int result1=linear_search(a,190000,22);
	int time1_E=clock();
	printf("FOUND_RESULT=%d\n",result1);
	printf("TIME_ELAPSED_MS: %d\n",time1_E-time1_S);
	printf("3. BETTER_SEARCH\n");
	int time2_S=clock();
	int result2=better_search(a,190000,22);
	int time2_E=clock();
	printf("FOUND_RESULT=%d\n",result2);
	printf("TIME_ELAPSED_MS: %d\n",time2_E-time2_S);
	printf("4. SENTINEL_LINEAR_SEARCH\n");
	int time3_S=clock();
	int result3=sentinel_linear_search(a,190000,22);
	int time3_E=clock();
	printf("FOUND_RESULT=%d\n",result3);
	printf("TIME_ELAPSED_MS: %d\n",time3_E-time3_S);
	return 0;
}


网友评论    (发表评论)


发表评论:

评论须知:

  • 1、评论每次加2分,每天上限为30;
  • 2、请文明用语,共同创建干净的技术交流环境;
  • 3、若被发现提交非法信息,评论将会被删除,并且给予扣分处理,严重者给予封号处理;
  • 4、请勿发布广告信息或其他无关评论,否则将会删除评论并扣分,严重者给予封号处理。


扫码下载

加载中,请稍后...

输入口令后可复制整站源码

加载中,请稍后...