'Steps of counting sort in MPI: segmentation fault 11
I have this code that implements the counting sort in C:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main(){
//create an array of N random elements
int N = 100;
int my_array[N];
srand(time(NULL));
int i;
for (i=0; i<N; i++){
my_array[i]=rand()%100 + 1;
}
//print the array
for (i=0; i<N; i++){
printf("%d ", my_array[i]);
}
clock_t start_time, end_time;
double computation_time;
start_time = clock();
//define the minimum and the maximum as the first element of the array
int min_array=my_array[0];
int max_array=my_array[0];
printf("\n--------------\n");
//find the minimum and the maximum of the array
for(i=0; i<N; i++){
if(my_array[i]<min_array){
min_array=my_array[i];
}
else if(my_array[i]>max_array){
max_array=my_array[i];
}
}
//check if it worked
printf("max_array %d\n", max_array);
printf("min_array %d\n", min_array);
//
int range_array;
range_array = max_array - min_array + 1;
int count_array[range_array];
for(i=0; i<range_array;i++)
count_array[i]=0;
int j=0;
for(int i=0; i<N; i++){
count_array[my_array[i]-min_array]=count_array[my_array[i]-min_array]+1;
}
int z = 0;
for(i=min_array; i<=max_array; i++){
for(j=0; j<count_array[i-min_array];j++)
my_array[z++]=i;
//z=z+1;
}
end_time = clock();
computation_time = ((double) (end_time - start_time)) / CLOCKS_PER_SEC;
printf("Time Taken: %lf \n", computation_time);
for(i=0; i<N; i++){
printf("%d ", my_array[i]);
}
printf("\n--------------\n");
printf("Time Taken: %lf \n", computation_time);
}
I have to implement this code using MPI. Basically, the first step of counting sort is to find the maximum and the minimum of an array. So I started trying to implement this search for max and min using MPI:
// First call MPI_Init
MPI_Init(&argc, &argv);
t1 = MPI_Wtime();
// Get my rank
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
// Get the number of ranks
MPI_Comm_size(MPI_COMM_WORLD,&n_ranks);
//define the minimum and the maximum as the first element of the array
int min_array=my_array[0];
int max_array=my_array[0];
printf("\n--------------\n");
MPI_Reduce(my_array,&min_array,N,MPI_INT,MPI_MIN,0,MPI_COMM_WORLD);
MPI_Reduce(my_array,&max_array,N,MPI_INT,MPI_MAX,0,MPI_COMM_WORLD);
if (rank == 0){
printf("Max_value is: %d\n", max_array);
printf("Min_value is: %d\n", min_array);
}
Inside the main, just after the creation of the array, I have written these lines of code in order to do this task of min and max. However, if I try to execute sometimes it compiles (but the search is wrong) and sometimes appears Segmentation fault: 11
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|