D. Zsolt
D. Zsolt

Reputation: 97

How can I implement a merge sort by using fork processes?

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);

        } 
    }

}

Upvotes: 1

Views: 4269

Answers (1)

SiggiSv
SiggiSv

Reputation: 1229

As has been pointed out, forked processes can neither see nor alter the memory space of each other.

You have (at least) three options:

Upvotes: 1

Related Questions