二分法練習題目

二分查找法

1.      二分查找的數組是有序的

2.      二分查找能夠有效的減少有序數組的查詢次數

3.      題目

利用二分查找法,查找某個數,如果存在則輸出這個數,如果不存在,輸出比它大的最小的數,輸出比它小的最大的數,如果該數不在這個數組的範圍內,就會報錯

#include<stdio.h>
#include<stdlib.h>
void init(int array[],int num);
int binaryFind(int array[],int num,int findNum);
//06
void main()
{
	int ret = 1;
	int a[10] ={0};
	init(a,sizeof(a)/sizeof(*a));
	int findNum = 0;
	printf("輸入你想要查找的數:");
	scanf("%d",&findNum);
    ret = binaryFind(a,sizeof(a)/sizeof(*a),findNum);
	if (ret == -1)
	{
		printf(" error: %d  can't find the number %d",ret,findNum);
	}
	else
	{
		printf("the label is %d",ret+1);
	}
	system("pause");
}
//數組輸入和排序
void init(int array[],int num)
{
   int temp = 0;
   //數組的錄入
   for (int i = 0;i< num;i++)
   {
	   printf("請輸入%d個數",i+1);
	   scanf("%d",&array[i]);
   }
   //冒泡排序
   for(int i = 0;i< num;i++)
   {
      for(int j = 0;j<num-i-1;j++)
	  {
		  if(array[j]>array[j+1])
		  {
			  temp = array[j];
			  array[j] = array[j+1];
			  array[j+1] = temp;

		  }
	  }
   }
}

//二分查找
int binaryFind(int array[],int num,int findNum)
{
	int ret = -2;
	if (array == NULL)
	{
		return ret = -1;
	}
	//二分查找主要算法
	int begin = 0;
	int end   = num -1;
	int nowLable = 0;

	if (findNum < array[0] || findNum > array[num -1])
	{
		return ret = -1;
	}
	while(begin <= end)
	{
		nowLable = (begin + end)/2;
		if (array[nowLable]== findNum)
		{
			return nowLable;
		}
		if (array[nowLable]>findNum)
		{
			end = nowLable - 1;
		}else
		{
	        begin = nowLable + 1;
		}
	}

	if (array[nowLable] > findNum)
	{
		printf("the biger number is %d\n",array[nowLable]);
		printf("the lower number is %d\n",array[nowLable -1]);
	}
	else
	{
		printf("the biger number is %d\n",array[nowLable+1]);
		printf("the lower number is %d\n",array[nowLable]);
	}


	return ret;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章