欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C语言->二分查找

程序员文章站 2024-03-17 14:52:28
...

方法1: 循环

#define  _CRT_SECURE_NO_WARNINGS
#include "stdio.h"
#include "stdlib.h"

int binarySearch(int *arr, int findNum,int length)
{
	int head = 0;
	int back = length - 1;
	while (head <= back) {
		int mid = (head + back) / 2;
		if (arr[mid] < findNum)
		{
			head = mid + 1;
		}
		else if(arr[mid] > findNum) 
		{
			back = mid - 1;
		}
		else
		{
			return mid;
		}
	}
	return -1;


}


void main()
{
	int data[] = { 1, 3, 6, 7, 9, 12, 14, 16, 17, 18, 20, 21, 22, 23, 30, 32, 33, 35 };
	int length = sizeof(data) / sizeof(int);
	int findABC = binarySearch(data, 35,length);
	if(findABC != -1)
	{
		printf("找到了!!!元素ID为%d, 元素为%d", findABC,data[findABC]);
	}
	else
	{
		printf("没找到啊!");
	}
	system("pause");
}

方法2:递归

int * binarySearchStack(int *arr, int findNum, int length)
{
    int* head = arr;
    int* back = arr + length - 1;
    int* mid = arr + (length - 1) / 2;
    if ((back - head) >= 0)
    {
        if (*mid == findNum)
        {
            printf("找到了");
            return mid;
        }
        else if (*mid < findNum)
        {
            binarySearchStack(mid +1, findNum, back - mid);
        }
        else
        {
            binarySearchStack(arr, findNum, mid - head);
        }
    }
    else
    {
        printf("找不到");
        return NULL;
    }


}
void main()
{
    int data[] = { 1, 3, 6, 7, 9, 12, 14, 16, 17, 18, 20, 21, 22, 23, 30, 32, 33, 35 };
    int length = sizeof(data) / sizeof(int);
    int* findABC = binarySearchStack(data, 99, length);
    if (findABC != NULL)
    {
        printf("找到了!!!元素ID为%d, 元素为%d", findABC-data, *findABC);
    }
    else
    {
        printf("没找到啊!");
    }
    system("pause");
}