Using fork processes, I want to implement merge sort. I want to divide and conquer the sorting of data in an array: I want to divide by give each half to a child process, then conquer by making the parent process merge these parts.
The following code works just for two numbers, for three or more numbers, the array does not change. Why?
void sort(int low, int high, int a[100], int b[100]) {
int mid;
pid_t pid1, pid2;
if(low < high) {
mid = (low + high) / 2;
pid1=fork();
if (pid1<0) exit(0);
if (pid1==0) { //first child process
sort(low, mid,a,b); //first half
exit(0);
}
else wait(NULL);
pid2=fork();
if (pid2<0) exit(0);
if (pid2==0){ //second child process
sort(mid+1, high,a,b); //second half
exit(0);
}
else wait(NULL);
if (pid1>0 && pid2>0)
{
merging(low, mid, high,a, b);
}
}
}