在 C 程序中使用 pthread 进行二分查找?


我们知道,二分查找方法是最适合、最有效的排序算法之一。这可用于经过排序的序列。该算法很简单,它可以找到中间元素,然后将列表分成两部分,然后或向左子列表移动或向右子列表移动。

我们了解它的算法。现在,我们将了解如何在多线程环境中使用二分查找技术。线程数量取决于系统中的内核数量。我们来看一下代码,以了解这个想法。

示例

#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 < high
   // or key is found in any portion of array
   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

更新于:20-Aug-2019

469 次浏览

启动您的 职业

完成本课程获取认证

开始学习
广告