merge

i am trying to make a program to merge two sorted lists into a single sorted list but there is a run time error please help!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <stdio.h>
void merge(int a1[],int n,int a2[],int m)
{

    int i=0,j=0,k=0,t;
    int a[20];
    while(i<n || j<m)
    {
        if(i<n)
        {
            if(a1[i]>a2[j])
            {
                a[k]=a2[j];
                ++k;
                ++j;
               
            }
        }
        else
        {
            if(j<m)
            {
                a[k]=a1[i];
                ++i;
                ++k;
              
            }
        }
    }
    for(t=0;t<k;t++)
    {
        printf("%d\t",a[k]);
    }
}
int main()
{
    int a1[]={25,29,34,45};
    int a2[]={28,31,33,39,40,42};
    merge(a1,4,a2,6);
}
Use vector(from #include <vector>) and sort(from #include <algorithm>) instead.

Something like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <vector>
using std::vector
#include <algorithm>
using std::sort;


vector<int> ivect;
ivect.push_back(25);
ivect.push_back(29);
ivect.push_back(34);
ivect.push_back(45);

vector<int> ivect2;
ivect2.push_back(28);
ivect2.push_back(31);
ivect2.push_back(33);
ivect2.push_back(39);
ivect2.push_back(40);
ivect2.push_back(42);


vector<int> finalList;

for(int i=0; i<ivect.size(); ++i){
  finalList.push_back(ivect[i]); //add the first list to finalList
}

for(int i=0; i<ivect2.size(); ++i){
  finalList.push_back(ivect2[i]); //add the second list to finalList
}

sort(finalList.begin(), finalList.end()); //sort finalList
Last edited on
@mehak

To keep it simpler, I would copy the two arrays into the larger array, and THEN sort it with a bubble sort.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <stdio.h>
#include <iostream>

using std::cout;
using std::endl;


void merge(int a1[],int n,int a2[],int m)
{

 int i=0,j=0,k=0,t,total=n+m;
 int a[20];
 for(int x=0; x<n;x++)
	a[x]=a1[x];
for(int x=0; x<m;x++)
	a[x+n] = a2[x]; // Combine both arrays into the one array
 for(t=0;t<total;t++)
 {
	printf("%d\t",a[t]); // Print out un-sorted aray
 }

 for(int i = 1; i < total; i++) // Sort the larger array
	{
		for(int j = 0; j < total - 1; j++)
		{
			if(a[j] > a[j+1])
			{
				int temp = a[j];
				a[j] = a[j+1];
				a[j+1] = temp;
			}
		}
}
 for(t=0;t<total;t++)
 {
	printf("%d\t",a[t]); // Print out sorted array
 }
}

int main()
{
 int a1[]={25,29,34,45};
 int a2[]={28,31,33,39,40,42};
 merge(a1,4,a2,6);
}
Last edited on
Topic archived. No new replies allowed.