天天看點

OpenMp之快速排序

#include <stdio.h>  
#include<stdafx.h>
#include<iostream>
#include <stdlib.h>  
#include <time.h>  
#include "omp.h"  
using namespace std;
//int count=0;  
	void swap(int &a, int &b)//  
	{  
		int tmp;  
		tmp = a;  
		a = b;  
		b = tmp;  
	}  
	void quicksort(int *A,int l, int u)  
	{  
		int i,m,k;  
		if (l >= u) return;   
		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]);    
		quicksort(A,l, m-1);  
		quicksort(A,m+1, u);  
	}  
	void main(int argc, char *argv)   
	{  
		omp_set_num_threads(2);//----------------設定線程數為2,因為是雙核的CPU  
		int k=0,i=0;  
		int m=0,n=0;  
		double cost=0;  
		int len=10000;  
		int short_len=len/2;  
		int B[10000],C[10000],D[5000],E[5000];//--------将B[]分為兩個小的數組,并行的對他們調用快速排序算法  
		#pragma omp parallel default(none) shared(B,C,len) private(i)//---這個for循環是并行的  
		{  
			int j=50000;
		#pragma omp for  
		for(i=0;i<len;i++)  
			{  
				B[i]=j--;
				C[i]=j--;
				//初始化B[],C[]數組  
			}  
		}  
		clock_t begin = clock();//----------------計時開始點  
		#pragma omp parallel default(none) shared(B,D,E,short_len) private(i)//---這個for循環是并行的  
		{  
		#pragma omp for  
			for(i=0;i<short_len;i++)//---這個for循環是并行的  
			{  
				D[i]=B[i];//将B[]的前5000個數放入D[]  
				E[i]=B[i+5000];//将B[]的後5000個數放入E[]  
			}  
		}  
		#pragma omp parallel default(none) shared(E,D,short_len) //private(i)------快速排序的并行region  
		{  
			#pragma omp parallel sections  
			{  
				#pragma omp section  
					quicksort(D, 0, short_len-1);//對D[]排序  
				#pragma omp section  
					quicksort(E, 0, short_len-1);//對E[]排序  
			}  
		}    
		for(;k<len;k++)//----------将D[]和E[]進行歸并排序放入B[]裡面  
		{    
		if(m<short_len && n<short_len)  
		{  
			if(D[n]<=E[m])  
			{  
				B[k] = D[n];  
				n++;  
			}  
			else  
			{  
				B[k]=E[m];  
				m++;  
			}  
		}  
			if(m==short_len || n==short_len)  
			{  
				if(m==short_len)  
				B[k]=E[m];  
				else  
				B[k]=D[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]=D[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]=E[m];  
			m++;  
			k++;  
		}  
		}//----------------------------歸并算法結束  
		clock_t end = clock();//----------------計時結束點  
		cost = (double)(end - begin);  
		cout<<"并行時間"<<cost<<endl;
		//串行開始
		begin=clock();
		quicksort(C, 0, len-1);
		end = clock();
		cost = (double)(end - begin);  
		cout<<"串行時間"<<cost<<endl;
		system("pause");  
		} 
           
OpenMp之快速排序

繼續閱讀