
我们知道二分查找方法是一种最适合和有效的排序算法。这个算法适用于已排序的序列。算法很简单,它只是从中间找到元素,然后将列表分成两部分,并向左子列表或右子列表移动。
我们知道它的算法。现在我们将看到如何在多线程环境中使用二分查找技术。线程的数量取决于系统中存在的核心数。让我们看一下代码以了解思路。
示例
#include <iostream>
#define MAX 16
#define MAX_THREAD 4
using namespace std;
//place arr, key and other variables as global to access from different thread
int 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 key)
end = mid - 1;
else
start = mid + 1;
}
}
main() {
pthread_t threads[MAX_THREAD];
for (int i = 0; i <h2>输出</h2>
<pre class="brush:php;toolbar:false;">31 found in array
13万字C语言保姆级教程(深入):立即使用
在学习笔记中,你将探索c语言的核心概念和高级技巧!











