我很清楚这个代码很奇怪。一点点C,主要是C ++。我是C语言的新手,我不明白如何用C语言做特定的事情,所以我做了一个怪异的描写。
我想对并行的每一行进行快速排序。我正在尝试将行传递到函数中,但出现错误。我创建了一个动态数组,以便对每一行都有一个新的线程来对其进行快速排序-number of rows = number of threads
。每个线程应排序一行。您还必须在该站点的另一篇文章中也看到了这个quickSort实现。如果我正确执行所有操作,则只需要一些指导。
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
#include <time.h>
using namespace std;
int ParPartition(int *a, int p, int r);
void ParQuickSort(int *a, int p, int r);
int main()
{
int r = 0;
int c = 0;
int count = 0;
int rtemp = 0;
int cTemp = 0;
printf("Enter row and column respectively : ");
scanf_s("%d %d", &r, &c);
int** arr = new int*[r];
for (int i = 0; i < r; ++i)
arr[i] = new int[c];
srand(time(NULL));
for (int row = 0; row < r; row++)
{
for (int col = 0; col < c; col++)
{
arr[row][col] = rand();
count += arr[row][col];
}
}
cout << endl << r * c << " random numbers" << endl;
for (int row = 0; row < r; row++)
{
for (int col = 0; col < c; col++)
{
cout << arr[row][col] << "\t";
}
cout << endl;
}
cout << endl << "Total : " << count << endl;
ParQuickSort(arr[0][r], 0, c - 1);
for (int i = 0; i < c; i++)
{
}
for (int i = 0; i < r; i++)
{
delete[] arr[i];
}
delete[] arr;
system("pause");
}
int ParPartition(int *a, int p, int r)
{
int *b = new int[r - p];
int key = *(a + r); // use the last element in the array as the pivot
int *lt = new int[r - p]; // mark 1 at the position where its element is smaller than the key, else 0
int *gt = new int[r - p]; // mark 1 at the position where its element is bigger than the key, else 0
int cnt_lt = 0; // count 1 in the lt array
int cnt_gt = 0; // count 1 in the gt array
int j = p;
int k = 0; // the position of the pivot
// deal with gt and lt array
#pragma omp parallel for
for (j = p; j<r; ++j) {
b[j - p] = *(a + j);
if (*(a + j) < key) {
lt[j - p] = 1;
gt[j - p] = 0;
}
else {
lt[j - p] = 0;
gt[j - p] = 1;
}
}
// calculate the new position of the elements
for (j = 0; j<(r - p); ++j) {
if (lt[j]) {
++cnt_lt;
lt[j] = cnt_lt;
}
else
lt[j] = cnt_lt;
if (gt[j]) {
++cnt_gt;
gt[j] = cnt_gt;
}
else
gt[j] = cnt_gt;
}
// move the pivot
k = lt[r - p - 1];
*(a + p + k) = key;
// move elements to their new positon
#pragma omp parallel for
for (j = p; j<r; ++j) {
if (b[j - p] < key)
*(a + p + lt[j - p] - 1) = b[j - p];
else if (b[j - p] > key)
*(a + k + gt[j - p]) = b[j - p];
}
return (k + p);
}
void ParQuickSort(int *a, int p, int r)
{
int q;
if (p<r)
{
q = ParPartition(a, p, r);
#pragma omp parallel sections
{
#pragma omp section
ParQuickSort(a, p, q - 1);
#pragma omp section
ParQuickSort(a, q + 1, r);
}
}
}