我正在尝试使用OpenMP库中的pragma omp并行实现三元搜索算法。我正在使用递归,这是我在代码实现中到目前为止所达到的。
这是搜索功能:
int ternarySearch(int arr[], int size, int left, int right, int num)
{
if (left < 0 || right > size - 1 || left > right){
return -1;
}
else if (num == arr[left]){
return left-1;
}
else if (num == arr[right]){
return right-1;
}
else if (num < arr[left]){
return ternarySearch(arr, size, left - 1, right, num);
}
else if (num > arr[left] && num < arr[right]){
return ternarySearch(arr, size, left + 1, right - 1, num);
}
else if (num > arr[right]){
return ternarySearch(arr, size, left, right + 1, num);
}
}
以下是调用ternarySearch函数的main函数中的部分:
omp_set_num_threads(4);
int quarter = size / 4;
/*Using Recursion*/
cout << endl << "Parallel Using Recursion: " << endl << endl;
bool isFound = false;
double paraRecStartTime = omp_get_wtime();
#pragma omp parallel shared(isFound)
{
int id, start, end, left, right, result;
id = omp_get_thread_num();
start = id*quarter;
end = start + quarter;
left = (quarter / 3) + start;
right = end - (quarter / 3);
cout << id << endl;
result = ternarySearch(arr, end, left, right, num);
if(result != -1) {
cout << "Found by thread " << id << " in index " << result << endl;
isFound = true;
}
}
double paraRecRunTime = omp_get_wtime() - paraRecStartTime;
cout << "Ternary Search took " << paraRecRunTime << " sec using 4 threads." << endl << endl;
if (isFound == false) {
cout << "Number does not exist in the array." << endl << endl;
}
问题是在输出中,所有线程都找到了元素,而每个线程应该只给出一个数组的一部分,以便使用三元搜索算法进行搜索。有人可以帮我知道我哪里出错吗?
答案 0 :(得分:0)
进一步阅读OpenMP标准,并为此使用任务。它们比使用嵌套并行性更适合递归问题。