在C程序中使用pthread进行二进制搜索?
我们知道二进制搜索方法是最合适和有效的排序算法之一。这适用于排序的序列。该算法很简单,它只是从中间找到元素,然后将列表分为两部分,然后向左子列表或右子列表移动。
我们知道它的算法。现在我们将看到如何在多线程环境中使用二进制搜索技术。线程数取决于系统中存在的内核数。让我们看一下代码以获得想法。
示例
#include <iostream>#define MAX 16
#define MAX_THREAD 4
using namespace std;
//将arr,key和其他变量设置为全局变量以从不同线程访问
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) {
//有四个线程,每个线程都占列表的1/4-
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
//或键在数组的任何部分中找到
while (start < end && !found) { //if some other thread has got the element, it will stop
mid = (end - start) / 2 + start;
if (arr[mid] == key) {
found = true;
break;
}
else if (arr[mid] > 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进行二进制搜索? 的全部内容, 来源链接: utcz.com/z/340966.html