Problem Description:
Set a[0:k] and a[k+1:n-1] are sorted (0<=k<=n-1). Try to design an algorithm that merges these two sub arrays into a sorted array a[0:n-1. It is required that the algorithm use O (n) in the worst case and use only O (1) of the auxiliary space.
This topic is relatively simple, look at the code to know.
#include <stdio.h>
void Displayarray (int *parray, int nlen)
{
for (int i = 0; i < Nlen; ++i)
{
printf ("array[%d] =%d\n", I, parray[i]);
}
}
PArray1 and PArray2 are sorted arrays, requiring them to be merged into the Parray in order
The array after the sort does not have duplicate elements
void Mergearray (int *parray1, int nLen1, int *parray2, int nLen2, int *parray)
{
int I, j, N;
i = j = n = 0;
while (I < nLen1 && J < nLen2)//loop until the elements of an array have been copied
{
if (Parray1[i] < PARRAY2[J])//copy elements of Array1
{
parray[n++] = parray1[i++];
}
else if (Parray1[i] > Parray2[j])//copy elements of Array2
{
parray[n++] = parray2[j++];
}
else//equal element copy
{
parray[n++] = parray2[j++];
++i;
}
}
if (i = = nLen1)///If Array1 has been copied, copy array2 elements
{
while (J < NLen2)
parray[n++] = parray2[j++];
}
else//If Array2 has been copied, copy array1 elements
{
while (I < NLEN1)
parray[n++] = parray1[i++];
}
}
int main ()
{
int array1[] = {1, 4, 5, 7};
int array2[] = {2, 3, 6, 8};
int array3[8];
Mergearray (Array1, 4, Array2, 4, array3);
printf ("Merge array:\n");
Displayarray (ARRAY3, 8);
return 1;
}