Binary search in C language (binary search) (vs2013)


Binary search

  Binary search is also called Binary Search, which is an efficient search method. However, the binary search requires that the linear table must adopt a sequential storage structure , and the elements in the table are arranged in order by keywords . If the element to be found is in the table, then return it, if the element is not in the table, return NULL.

Comparison of sequential search and binary search

Why is binary search an efficient search method?

First, let's look at the sequential search . For example,
we have:
      3, 6,
9 , 11, 12, 15, 19, 20, 22, these nine numbers.
   I choose one of the numbers at will, suppose it is 11, and we have to find 11 from these nine numbers. If the number found is 11, then it is found. If there is no 11 among the nine numbers, it is not found.
   Suppose you start from the first one. The
first time: 3, wrong. The
second time: 6, wrong. The
third time: 9, wrong. The
fourth time: 11, found!
   This is a sequential search . Only one number can be excluded for each search. Now we are looking for 11, which only takes four times, but if we are looking for 25, it will be nine times. If there are more numbers, then It takes more times.


So what is the more efficient binary search ?
  Assuming that the number we are looking for is still 11, the
first time: we take the middle number of these nine numbers: 12. 11<12, which is smaller, then we can exclude the right part of 12.
Second time: We take the middle number of the left part of 12: 9. 11>9, which is bigger, then we can exclude the left part of 9.
The third time: We take the middle number of the right part of 9: 11. 11=11, we found it.
   This method is much faster than the above sequential search. There may be only one difference in this example, but when there are more numbers? The binary search will be much faster, this is the binary search.

use

Let's take a look at the application of binary search in the c language, here I am using VS2013.

#include <stdio.h>
int main()
{
    
    
	char arr[] = {
    
     1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
	//tofind表示要找的数字
	int tofind = 7;
	//数组最左边元素的下标
	int left = 0;
	//数组最右边元素的下标
	int right = sizeof(arr) / sizeof(arr[0]) - 1;
	//sizeof(arr)是计算arr的字节
	//sizeof(arr[0])是计算数组中第一个的字节
	//两者相除就是数组长度
	while (left <= right){
    
    
		int mid = (left + right) / 2;
		if (tofind > arr[mid]){
    
    
		//说明你要查找的数在mid 的右边,
		//因此需要向右递归查找
			left = mid + 1;
		}
		else if (tofind < arr[mid]){
    
    
			right = mid - 1;
		}
		else{
    
    
			printf("找到了,下标是:%d\n", mid);
			break;
		}
	}
	if (left>right){
    
    
		printf("找不到");
	}
	system("pause");
	return 0;
}

Guess you like

Origin blog.csdn.net/qq_34270874/article/details/109139685