使用C语言编写的二分查找程序,使用pthread进行多线程处理

使用c语言编写的二分查找程序,使用pthread进行多线程处理

我们知道二分查找方法是一种最适合和有效的排序算法。这个算法适用于已排序的序列。算法很简单,它只是从中间找到元素,然后将列表分成两部分,并向左子列表或右子列表移动。

我们知道它的算法。现在我们将看到如何在多线程环境中使用二分查找技术。线程的数量取决于系统中存在的核心数。让我们看一下代码以了解思路。

示例

#include #define MAX 16#define MAX_THREAD 4using namespace std;//place arr, key and other variables as global to access from different threadint arr[] = { 1, 6, 8, 11, 13, 14, 15, 19, 21, 23, 26, 28, 31, 65, 108, 220 };int key = 31;bool found = false;int part = 0;void* binary_search(void* arg) {   // There are four threads, each will take 1/4th part of the list   int thread_part = part++;   int mid;   int start = thread_part * (MAX / 4); //set start and end using the thread part   int end = (thread_part + 1) * (MAX / 4);   // search for the key until low < high   // or key is found in any portion of array   while (start  key)         end = mid - 1;      else         start = mid + 1;   }}main() {   pthread_t threads[MAX_THREAD];   for (int i = 0; i < MAX_THREAD; i++)      pthread_create(&threads[i], NULL, binary_search, (void*)NULL);   for (int i = 0; i < MAX_THREAD; i++)      pthread_join(threads[i], NULL); //wait, to join with the main thread   if (found)      cout << key << " found in array" << endl;   else      cout << key << " not found in array" << endl;}

输出

31 found in array

以上就是使用C语言编写的二分查找程序,使用pthread进行多线程处理的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1443403.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年12月17日 20:05:03
下一篇 2025年12月17日 20:05:17

相关推荐

发表回复

登录后才能评论
关注微信