折半查找算法
#include<stdio.h>
int main()
{
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int left = 0;
int right = sizeof(arr) / sizeof(arr[0]) – 1;
int key = 7;
int mid = 0;
while (left <= right)
{
mid = (left + right) / 2;
if (arr[mid] < key)
{
left = mid + 1;
}
else if (arr[mid]>key)
{
right = mid – 1;
}
else
break;
}
if (left <= right)
printf(“找到了,下标是%d\n”, mid);
else
printf(“没找到\n”);
return 0;
}
二分查找函数
int bin_search(int arr[], int left, int right, int key)
{
int mid = 0;
while (left <= right)
{
mid = (left + right) >> 1;
if (arr[mid] < key)
{
left = mid + 1;
}
else if (arr[mid]>key)
{
right = mid – 1;
}
else
return mid;
}
return -1;
}
猜数字游戏实现
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
void menu()
{
printf(“###############################################################\n”);
printf(“#################### 1. play #############################\n”);
printf(“#################### 2. exit #############################\n”);
printf(“###############################################################\n”);
}
void game()
{
int random_num = rand() % 100 + 1;
int input = 0;
while(1)
{
printf(“请输入猜的数字:\n”);
scanf(“%d”, &input);
if (input > random_num)
{
printf(“猜大了\n”);
}
else if (input < random_num)
{
printf(“猜小了\n”);
}
else
{
printf(“恭喜你猜对了\n”);
break;
}
}
}
int main()
{
int input = 0;
srand((unsigned)time(NULL));
do
{
menu();
printf(“请选择:\n”);
scanf(“%d”, &input);
switch (input)
{
case 1:
game();
break;
case 2:
break;
default:
printf(“选择错误,请重新输入!\n”);
}
}
while (input);
return 0;
}