C程序设计语言 Exercise 3-1
来源:互联网 发布:java高级面试题2017 编辑:程序博客网 时间:2024/05/08 02:23
Exercise 3-1. Our binary search makes two tests inside the loop, when one would suffice (at
the price of more tests outside.) Write a version with only one test inside the loop and
measure the difference in run-time.
the price of more tests outside.) Write a version with only one test inside the loop and
measure the difference in run-time.
#include "stdio.h"#include "time.h"#define MAX_LENGTH 2000000int BinSearch1(int,int[],int);int BinSearch2(int,int[],int);intmain(){int v[MAX_LENGTH] = {0};int i = 0;for (i = 0;i < MAX_LENGTH;i++) {v[i] = i;}clock_t stStartTime = clock();for (i = 0;i < MAX_LENGTH;i++) {BinSearch1(i,v,sizeof(v)/sizeof(*v));}printf("BinSearch1==>%f\n",((double)(clock() - stStartTime)) / CLOCKS_PER_SEC);stStartTime = clock();for (i = 0;i < MAX_LENGTH;i++) {BinSearch2(i,v,sizeof(v)/sizeof(*v));} printf("BinSearch2==>%f\n",((double)(clock() - stStartTime)) / CLOCKS_PER_SEC); return 0;}intBinSearch1(int x,int v[],int n){int start = 0;int end = n - 1;int middle = 0;while(start <= end) {middle = (start + end) / 2;if(v[middle] < x) {start = middle + 1;}else if(v[middle] > x){end = middle - 1;}else {return middle;}}return -1;}intBinSearch2(int x,int v[],int n){int start = 0;int end = n - 1;int middle = 0;while(start <= end && v[middle] != x){middle = (start + end) / 2;if(v[middle] < x) {start = middle + 1;}else{end = middle - 1;}}return v[middle] == x ? middle: -1;}
- C程序设计语言 Exercise 3-1
- C程序设计语言 Exercise 2-9
- C程序设计语言 Exercise 2-10
- C程序设计语言练习3-1
- C程序设计语言读书笔记(3)
- c程序设计语言笔记3
- C程序设计语言3-2
- c程序设计语言读书笔记(1)
- c程序设计语言笔记1
- C程序设计语言笔记1
- c 程序设计语言 1-9
- K&R C Exercise 3-1 Solution
- C - The C Answer (2nd Edition) - Exercise 1-3
- C程序设计语言练习3-3
- 《C程序设计语言》练习3-3
- C程序设计语言练习2-3
- C程序设计语言练习3-2
- C程序设计语言练习3-4
- linux内核等待队列的使用
- Android 程序的安装、卸载和更新
- 从最大似然到EM算法浅解
- WP 布局
- 关于JBPM
- C程序设计语言 Exercise 3-1
- SpringSecurity
- linux应用层定时器
- 看老外程序员如何向妻子解释设计模式
- JAVA注解编程
- 黑马程序员 Java基础 --->7K面试题之银行业务调度系统
- Oracle体系结构及备份(十四)——bg-dbwr
- 通过Android trace文件分析死锁ANR
- wpf dll和exe合并成一个新的exe