#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
#define N 1000
#define NUM_BUCKETS 10
int main(int argc, char** argv) {
MPI_Init(&argc, &argv);
int rank, size;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
int i, start, end;
int data[N];
int sorted[N];
int bucket[NUM_BUCKETS][N];
int bucket_count[NUM_BUCKETS];
int bucket_rank[NUM_BUCKETS];
int bucket_size[NUM_BUCKETS];
int bucket_end[NUM_BUCKETS];
if (rank == 0) {
for (i = 0; i < N; i++) {
data[i] = rand() % 1000;
}
}
start = rank * (N / size);
end = (rank + 1) * (N / size);
MPI_Scatter(data, end - start, MPI_INT, bucket[rank], end - start, MPI_INT, 0, MPI_COMM_WORLD);
for (i = 0; i < NUM_BUCKETS; i++) {
bucket_count[i] = 0;
bucket_rank[i] = i % size;
bucket_size[i] = (i + size) % size;
bucket_end[i] = bucket_rank[i] * (bucket_size[i] + 1);
}
for (i = start; i < end; i++) {
int index = bucket[rank][i - start];
bucket[bucket_rank[index]][bucket_count[index]] = bucket[rank][i - start];
bucket_count[index]++;
if (bucket_count[index] == bucket_size[index]) {
MPI_Send(bucket[bucket_rank[index]], bucket_count[index], MPI_INT, bucket_rank[index], 0, MPI_COMM_WORLD);
bucket_count[index] = 0;
} else if (bucket_count[index] == bucket_end[index]) {
MPI_Send(NULL, 0, MPI_INT, bucket_rank[index], 0, MPI_COMM_WORLD);
bucket_count[index] = 0;
} else if (bucket_count[index] == (bucket_size[index] + 1) * size / 2) {
for (int j = 0; j < size; j++) {
if (bucket[j][bucket_count[index]] != 0) {
MPI_Send(&bucket[j][bucket_count[index]], 1, MPI_INT, bucket_rank[index], 0, MPI_COMM_WORLD);
}
}
bucket_count[index] = 0;
}
}
MPI_Gather(bucket[rank], end - start, MPI_INT, sorted, end - start, MPI_INT, 0, MPI_COMM_WORLD);
if (rank == 0) {
// Combine and print the sorted array
printf("Sorted array: ");
for (i = 0; i < N; i++) {
printf("%d ", sorted[i]);
}
printf("\n");
}
MPI_Finalize();
return 0;
}
Bucket Sort MPI 程序
最新推荐文章于 2024-05-21 19:48:43 发布