OpenMP: OpenMP並行快速排序演算法

來源:互聯網
上載者:User

主要利用了OpenMP裡面的#omp parallel sections將對兩個子數組的快速排序函數用兩個線程並行化執行,至於線程的建立和銷毀我們不用管,只要告訴編譯器哪裡的代碼需要並存執行就可以了,具體請看OpenMP資料。

#include <stdio.h>#include <stdlib.h>#include <time.h>#include "omp.h"//int count=0;void swap(int &a, int &b)//{int x;x = a;a = b;b = x;}int randint(int a,int b){int e=0;e=b-a;return rand() % e + a;}void quicksort(int *A,int l, int u){int i,m,k;if (l >= u) return;// k=randint(l, u);//// swap(A[l],A[k]);//這兩行實現了隨機化m = l;for (i = l+1; i <= u; i++)if (A[i] < A[l])/*不管是選第一個元素作為pivot還是最後一個作為pivot,假如我們想得到的是從小到大的序列,那麼最壞的輸入//情況就是從大到小的;如果我們想得到從大到小的序列,那個最壞的輸入情況就是從小到大的序列*/swap(A[++m], A[i]);swap(A[l], A[m]);// count += u-l;//用於統計比較次數,來自《代碼之美》quicksort(A,l, m-1);quicksort(A,m+1, u);}void main(int argc, char *argv) {omp_set_num_threads(2);//----------------設定線程數為2,因為是雙核的CPUint j=50000,k=0,i=0;int m=0,n=0;clock_t begin, end;double cost;srand((unsigned)time( NULL ));int len=50000;int short_len=len/2;int B[50000],C[25000],D[25000];//--------將B[]分為兩個小的數組,並行的對他們調用快速排序演算法#pragma omp parallel default(none) shared(B,len) private(i)//---這個for迴圈是並行的{#pragma omp forfor(i=0;i<len;i++){B[i]=j--;//初始化B[]數組}}begin = clock();//----------------計時開始點#pragma omp parallel default(none) shared(B,C,D,short_len) private(i)//---這個for迴圈是並行的{#pragma omp forfor(i=0;i<short_len;i++)//---這個for迴圈是並行的{C[i]=B[i];//將B[]的前25000個數放入C[]D[i]=B[i+25000];//將B[]的後25000個數放入D[]}}#pragma omp parallel default(none) shared(C,D,short_len) //private(i)------快速排序的並行region{#pragma omp parallel sections{#pragma omp sectionquicksort(C, 0, short_len-1);//對C[]排序#pragma omp sectionquicksort(D, 0, short_len-1);//對D[]排序}}printf("/n");// begin = clock();for(;k<len;k++)//----------將C[]和D[]進行歸併排序放入B[]裡面{//if(C[k]<D[k])if(m<short_len && n<short_len){if(C[n]<=D[m]){B[k] = C[n];n++;}else{B[k]=D[m];m++;}}if(m==short_len || n==short_len){if(m==short_len)B[k]=D[m];elseB[k]=C[n-1];k+=1;break;}}if(/*m==short_len &&*/ n<short_len){int tem=short_len-n;for(int p=0;p<tem;p++){B[k]=C[n];n++;k++;}}else if(/*n==short_len &&*/ m<short_len){int tem=short_len-m;for(int q=0;q<tem;q++){B[k]=D[m];m++;k++;}}//----------------------------歸併演算法結束end = clock();//----------------計時結束點cost = (double)(end - begin) / CLOCKS_PER_SEC;printf("%lf seconds/n", cost);//輸出運行intervalsystem("pause");}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.