[Algorithmic problem] merges two sorted arrays into another array

Source: Internet
Author: User
Tags arrays printf

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.