排序数组的二进制搜索

编程入门 行业动态 更新时间:2024-10-08 10:53:23
本文介绍了排序数组的二进制搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我需要基于排序的书本排列结果对书本列表进行二进制搜索的帮助.我仍然是该领域的新手,我的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?".

更多推荐

排序数组的二进制搜索

本文发布于:2023-11-29 06:11:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1645568.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!