C language - binary search and guessing number game

binary search

Topic: Find a specific number n in an ordered array.

First, let's define an array of 1···10, if 7 is the number we want to find, write the code as follows

#include <stdio.h>
int main()
{
    
    
	int arr[] = {
    
     1,2,3,4,5,6,7,8,9,10 };
	//  下标          0 1 2 3 4 5 6 7 8 9
	int k = 7;//k是要查找的数字
	int i = 0;
	int sz = sizeof(arr) / sizeof(arr[0]);
     //sz为数组元素个数
	int flag = 0;//
	for (i = 0; i < sz; i++)
	{
    
    
		if (k == arr[i])
		{
    
    
			flag = 1;
			printf("找到了,下标是:%d\n", i);
			break;
		}
	}
	if (flag == 0)
		printf("找不到\n");

	return 0;
}

But this code is relatively inefficient and needs to be looped multiple times, so we need to use a more efficient method:binary searchalso called(find in half)

The idea of ​​binary search

Give you an ordered sequence, compare the middle element with the target element, take half of it, discard the other half, and quickly narrow down the position of the target element. The main idea is still: quickly narrow the range where the target element is located.

Conditions for binary search

1. The sequence must be in order, either in ascending or descending order.
2. The sequence must store elements sequentially. The main purpose of storing elements sequentially is to quickly obtain intermediate elements (elements can be found by subscripting)

Implementation process of binary search

Analysis: Assuming that the number we are looking for is 7, we need to use the subscript to search during the search process. At this time, we define the left subscript as left, the right subscript as right, and the middle element subscript as mid, (left+right)/ 2=mid. When the first search does not find it, shorten the search range from the middle subscript to the left or right and continue to search until it is found.

  • Take the number 7 as an example: the first search (left+right)/2=(0+9)/2=4, the subscript is 4, the found number is 5, but it is not found at this time; the second search , because The number 5 is smaller than the number 7, so mid+1=left, right remains unchanged, search to the right, at this time (left+right)/2=(5+9)/2=7, the subscript is 7, the found number is 8, not found; the third search , because the number 8 is greater than the number 7, so mid-1=right, the left subscript remains unchanged, search to the left, at this time (left+right)/2=(5+6)/ 2=5, the subscript is 5, the found number is 6, the fourth search , because 6 is less than 7, so search to the right, (left+right)/2=(6+6)/2=6, subscript is 6 and the number found is 7.
    insert image description here

code example

#include <stdio.h>
int main()
{
    
    
	int arr[] = {
    
     1,2,3,4,5,6,7,8,9,10 };
	// 下标       0 1 2 3 4 5 6 7 8 9
	int k = 7;//k是要查找的数字
	int i = 0;
	int sz = sizeof(arr) / sizeof(arr[0]);
	//折半查找(二分查找),前提是数组有序
	int left = 0;
	int right = sz - 1;

	int flag = 0;
	while (left<=right)
	{
    
    
		int mid = (left + right) / 2;
		if (arr[mid] < k)
		{
    
    
			left = mid + 1;
		}
		else if (arr[mid] > k)
		{
    
    
			right = mid - 1;
		}
		else
		{
    
    
			printf("找到了,下标是:%d\n", mid);
			flag = 1;
			break;
		}
	}
	if (flag == 0)
		printf("找不到\n");

	return 0;
}

If left is a large number, right is also a large number, and left+right exceeds the maximum value that can be expressed by shaping, and the data overflows. At this time, what (left+right)/2 seeks is not the maximum value. At this time What should we do?
We divide the extra part by two and divide it equally, as shown in the figure
insert image description here

code modification

#include <stdio.h>
int main()
{
    
    
	int arr[] = {
    
     1,2,3,4,5,6,7,8,9,10 };
	//            0 1 2 3 4 5 6 7 8 9
	int k = 7;//k是要查找的数字
	int i = 0;
	int sz = sizeof(arr) / sizeof(arr[0]);
	//折半查找(二分查找),前提是数组有序
	int left = 0;
	int right = sz - 1;

	int flag = 0;
	while (left<=right)
	{
    
    
		int mid = left + (right - left) / 2;

		if (arr[mid] < k)
		{
    
    
			left = mid + 1;
		}
		else if (arr[mid] > k)
		{
    
    
			right = mid - 1;
		}
		else
		{
    
    
			printf("找到了,下标是:%d\n", mid);
			flag = 1;
			break;
		}
	}
	if (flag == 0)
		printf("找不到\n");

	return 0;
}

guess the number game

game instructions

1. The computer generates a random number from 1 to 100.
2. Guess the number,
if it is a big guess, it will tell you: if it is a big
guess, it will tell you if it is a small guess: if it is a small
guess, it will tell you if it is right: Congratulations, you are right

guess the number game ideas

  • First of all, you need to print a menu, choose to start the game or exit the game
  • Secondly, the game should be able to play a round after a round, for a loop, use the loop statement to build the framework

Code

print menu

void menu()
{
    
    
	printf("*****************************\n");
	printf("*********   1. play  ********\n");
	printf("*********   0. exit  ********\n");
	printf("*****************************\n");
}

print result
insert image description here

print main function

int main()
{
    
    
	int input = 0;
	do
	{
    
    
		menu();
		printf("请选择:>");
		scanf("%d", &input);
		switch (input)
		{
    
    
		case 1:
			printf("猜数字\n");
			break;
		case 0:
			printf("退出游戏\n");
			break;
		default:
			printf("选择错误\n");
			break;
		}
	} while (input);
	return 0;
}

At this point the game is too simple, choose 1 to start the game, so we define a game function game()

print game function

The first step of the game: generating random numbers
The rand() function is a function for generating random numbers, the header file is <stdlib.h>
rand will return a number between 0 and 327637
Use rand() with srand() , srand () is to set the random number generator. Generally, the timestamp is used as the time seed, so use the time function to obtain the time , and then convert the time function to (unsigned) type and pass it to the srand function
insert image description here
insert image description here

void game()
{
    
    
	//1. 生成随机数
	int ret = rand() % 100 + 1;//0~99+1-->1~100
	//2. 猜数字
	int guess = 0;
	while (1)
	{
    
    
		printf("请猜数字:>");
		scanf("%d", &guess);
		if (guess < ret)
		{
    
    
			printf("猜小了\n");
		}
		else if (guess > ret)
		{
    
    
			printf("猜大了\n");
		}
		else
		{
    
    
			printf("恭喜你,猜对了\n");
			break;
		}
	}
}

Overall code demo

#include <stdlib.h>
#include <stdio.h>
#include <time.h>

void menu()
{
    
    
	printf("*****************************\n");
	printf("*********   1. play  *******\n");
	printf("*********   0. exit  ********\n");
	printf("*****************************\n");
}
//
//rand函数会返回一个0~32767之间的随机数
//
//时间戳

void game()
{
    
    
	//1. 生成随机数
	int ret = rand() % 100 + 1;//0~99+1-->1~100
	//2. 猜数字
	int guess = 0;
	while (1)
	{
    
    
		printf("请猜数字:>");
		scanf("%d", &guess);
		if (guess < ret)
		{
    
    
			printf("猜小了\n");
		}
		else if (guess > ret)
		{
    
    
			printf("猜大了\n");
		}
		else
		{
    
    
			printf("恭喜你,猜对了\n");
			break;
		}
	}
}

int main()
{
    
    
	int input = 0;
	//设置了随机数的生成器
	srand((unsigned int)time(NULL));
    //给srand传一个时间戳,是生成的数字足够随机
	do
	{
    
    
		menu();
		printf("请选择:>");
		scanf("%d", &input);
		switch (input)
		{
    
    
		case 1:
			game();
			break;
		case 0:
			printf("退出游戏\n");
			break;
		default:
			printf("选择错误\n");
			break;
		}
	} while (input);
	return 0;
}

Game Effect Demonstration
insert image description here

Guess you like

Origin blog.csdn.net/2201_75366661/article/details/128838309