#include #include #include #include void print_list(int list[], int length, int total_number); void oddeven_s(int A[], int n); void Oddeven_sort(int length, int B[]); int Compare(const int *a, const int *b); /**********************************************************************/ main(int argc, char *argv[]) { int cpu_num; /* cpu 的數目 */ int my_rank; /* 自己 cpu 的編號 */ int i, j; int N=5, n=1; /* 造 n=2^N 個亂數的數列 */ int cpu_list_size; /* 每顆 cpu 裡分到的數列長度 */ int list_length; int *local_list, *temp_list; float totaltime, temp; clock_t start_time, end_time; /**** MPI 命令開始 ****/ MPI_Status status; MPI_Init(&argc, &argv); MPI_Comm_size (MPI_COMM_WORLD, &cpu_num); MPI_Comm_rank (MPI_COMM_WORLD, &my_rank); /**** 造亂數數列 ****/ for (i = 0; i < N; i++) n = (long)n * 2; cpu_list_size = (n / cpu_num); /* 每棵 cpu 要分的數列長度 */ local_list = malloc(n * sizeof(int)); temp_list = malloc(n * sizeof(int)); srand((time(NULL)+my_rank)*(my_rank+1)); for (i = 0; i < cpu_list_size; i++) /* 每棵 cpu 各自造 cpu_list_size 長度的數列 */ local_list[i] = rand(); /* */ /**** 印出亂數數列 ****/ /* if (my_rank == 0) printf("%d random numbers:\n",n); print_list(local_list, cpu_list_size, n); */ start_time=clock(); /**** 開始 odd-even merge sort ****/ for (i=1, list_length = cpu_list_size ; i < cpu_num; i = i*2, list_length = list_length *2) { if ( (my_rank) % (2*i) == 0) { oddeven_s(local_list, list_length); for (j=0; j 4) { Oddeven_sort(half_way, B); Oddeven_sort(half_way, B + half_way); } for (i = 0; i < half_way; i=i+2) if (B[i] < B[half_way + i]) { temp[i]=B[i]; temp[i+1]=B[half_way + i]; } else { temp[i]=B[half_way + i]; temp[i+1]=B[i]; } for (i = 1; i < half_way; i=i+2) if (B[i] < B[half_way + i]) { temp[half_way + i-1]=B[i]; temp[half_way + i]=B[half_way + i]; } else { temp[half_way + i-1]=B[half_way + i]; temp[half_way + i]=B[i]; } for (i=0; i 4) { Oddeven_sort(half_way, B); Oddeven_sort(half_way, B + half_way); } for (i=0; i