'Algorithm for the implementation of merge sort using link array(pointers)
int a[SIZE];
int link[SIZE];
int MergeLists(int i, int j)
{
int head;
int *pprev = &head;
while((i != -1) && (j != -1)){
if(a[i] <= a[j]){
*pprev = i;
pprev = &link[i];
i=*pprev;
} else {
*pprev = j;
pprev = &link[j];
j=*pprev;
}
}
if(i == -1)
*pprev=j;
else
*pprev=i;
printf("%d head",head);
return head;
}
int MergeSort(int low, int end)
{
int mid, i, j;
if((end - low) == 0){
return low;
}
if((end - low) == 1){
link[low] = -1;
return low;
}
if((end - low) == 2){
if(a[low] <= a[end-1]){
link[low] = end-1;
link[end-1] = -1;
return low;
} else {
link[end-1] = low;
link[low] = -1;
return end-1;
}
}
mid = (low+end)/2;
i = MergeSort(low, mid);
j = MergeSort(mid, end);
return MergeLists(i, j);
}
int main()
{
int i;
for(i=0;i<SIZE;++i)
{
printf("\nenter element number %d: ",i+1);
scanf("%d",&a[i]);
}
i = MergeSort(1, SIZE);
do{
printf("%3d", a[i]);
i = link[i];
}while(i != -1);
return 0;
}
to implement merge sort using link array(pinters) error is given below input 4 5 2 1 output 1 2 5 MergeLists() uses head for the start of a list (the old code uses link[0]), and -1 for the end of a list (the old code uses 0). This allows sorting of a[0] to a[n-1] (the old code was sorting a[1] to a[n], with a[0] unused).
Solution 1:[1]
Well, it seems to be a minor problem, just change the function call in main to
i = MergeSort(0, SIZE);
In C or C++, the index starts with 0, and it is also true when we try to write a function.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Teddy van Jerry |
