排序数组的二进制搜索 [英] Binary search of sorted array

查看:124
本文介绍了排序数组的二进制搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我需要基于排序的书本排列结果对书本列表进行二进制搜索的帮助.我仍然是该领域的新手,我的Bubble排序工作正常,但是我被Binary Search困住了,我的程序无法从Sorted List中找到合适的Book ID来显示与Book ID相关的输出.非常感谢您的建议.

Hi,

I need help for my binary search of Book list based on sorted book array result. I am still new in this field, my Bubble sort is working fine, but I got stuck at Binary Search, my program cannot find the appropriate book ID from the Sorted List for displaying output related to book ID. I really appreciate your advices.

void Swap(TYPE &first, TYPE &last)
{
	TYPE temp;
	temp = first;
	first = last;
	last = temp;
}





void BubbleSort(Book *array[], int size)
{	
	int smallest;
	for(int first = 0; first < size - 1; first++)
	{
		smallest = first;
		for(int current = smallest + 1; current < size; current++)
		{
			if(*array[current] < *array[smallest])
				smallest = current;
		}
		Swap(array[first],array[smallest]);
	}
}





bool BinarySeach(Book *array[], int size, unsigned int bookID, Book *sortedOutput)
{
	int first = 0;
	int last = size - 1;
	int middle;
	int position = -1;
 
	while(first <= last)
	{
		middle = (first + last)/2;
	        
                if(array[middle] == sortedOutput)
	        {
 		  position = middle;
		  return (true);
	        }
		else if(array[middle] > sortedOutput)
		{
		  last = middle - 1;
		}
		else
		{
		  first = middle + 1;
		}
	}
	return (false);
}



主程序输出



main program output

//sortedOutput(bookID,Bookname);
List of sorted Book 
101 - Dummy Adobe Photoshop
102 - HTML,CSS
103 - Visual Studio 2008
 
Please enter ID to search: 102
ID not found, please try again



感谢您的帮助



Thank you for your help

推荐答案

在以下行中:
In the line:
if(*array[middle] > sortedOutput)


您确定要使用间接运算符(*)吗?


are you sure you want the indirection operator (*)?


您的二进制搜索功能仅返回以下事实:它找到(或未找到)该项目,它不返回找到它的位置因此它的有用性降低为列表中的项目?",而不是项目在哪里?".
Your binary search function only returns the fact that it found (or did not find) the item, it does not return where it found it so it''s usefullness is reduced to just "Is the item in the list?", not "Where is the item?".


这篇关于排序数组的二进制搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆