OpenMP를 사용하여 C++에서 동시 quicksort를 구현했습니다.동시 퀵 소트의 구현이 맞습니까?
#include <omp.h>
#include <iostream>
#include <algorithm>
using namespace std;
void sort(int *a, int low, int high);
int partition(int *a, int low, int high);
class QuickSort {
private:
int *arr;
int len;
public:
void init();
void Sort();
void Display();
};
int main() {
cout << "Program implementing Quicksort." << endl;
QuickSort a;
a.init();
a.Sort();
a.Display();
}
void sort(int *a, int low, int high) {
if(high < low || low == high)
return;
if(high == low+1) {
if(a[low] > a[high])
swap(a[low], a[high]);
return;
}
int pivotidx = partition(a, low, high);
/*for(int i = 0; i < 5; ++i)
cout << a[i] << " ";
cout << endl;*/
cout << "Pivot element has been placed at correct position: " << pivotidx << " by thread " << omp_get_thread_num() << endl;
#pragma omp parallel sections
{
#pragma omp section
{
sort(a, low, pivotidx);
}
#pragma omp section
{
sort(a, pivotidx+1, high);
}
}
}
int partition(int *a, int low, int high) {
int pivot = low;
int pivotval = a[low];
int leftpointer = low;
int rightpointer = high;
while(leftpointer < rightpointer) {
while(a[leftpointer] <= a[pivot] && leftpointer <= high)
++leftpointer;
if(leftpointer > high)
--leftpointer;
while(a[rightpointer] >= a[pivot] && rightpointer >= low)
--rightpointer;
if(rightpointer < low)
++rightpointer;
if(leftpointer < rightpointer)
swap(a[leftpointer], a[rightpointer]);
}
a[low] = a[rightpointer];
a[rightpointer] = pivotval;
return rightpointer;
}
void QuickSort::init() {
cout << "Enter the number of elements in the array: ";
cin >> len;
cout << "Enter the elements of the array: ";
arr = new int[len];
for(int i = 0; i < len; ++i)
cin >> arr[i];
}
void QuickSort::Sort() {
sort(arr, 0, len-1);
}
void QuickSort::Display() {
cout << "Sorted array is: " << endl;
for(int i = 0; i < len; ++i)
cout << arr[i] << " ";
cout << endl;
}
정확히 정렬되어 있지만 실제로 여러 코어에서 실행 중인지 잘 모르겠습니다. 이것을 어떻게 확인할 수 있습니까? 또한, 내 병렬 코드는 상단 대답 here에있는 것과 매우 유사합니다. 거기에 결국 두 스레드보다 병렬 처리를 추출 할 수 없다는 언급이있다 : 그것은 더 많은 스레드와 함께 실행되면, 다른 스레드가 할 일이 없어 그냥 유휴 앉아있을 것입니다. 왜 그래야만하지?
병렬 섹션에는 2 개의 하위 섹션이 있습니다. 각 하위 섹션은 하나의 스레드에 의해 실행됩니다. 따라서 빠른 정렬의 각 분할 단계마다 최대 병렬 처리 2를 얻을 수 있습니다. 그러나 이것이 원하는 것입니다. 첫 번째 잘라내 기는 스레드 1,2를 만듭니다. 1은 3과 4를 스폰합니다. 2는 5와 6을 스폰합니다. 내가 잘못하지 않은 경우 –
@SrinivasSuresh 중첩 된 OpenMP가 활성화되어 있지 않으면 추가 스폰이 발생하지 않습니다. –
나는 당신이 옳다고 믿습니다. –