merge sort two arrays

closed account (367L3TCk)
I have a problem with this code, I can not get the right sorted number. if I enter for the first array: 5... 5 4 3 2 1 and then for the second array:4...9 8 7 6.

it will print out this 5 4 3 2 1 9 8 7 6.
Needs to be in ascending order.

Last edited on
Try to find the smalest value of both of the array first, then add it to array3

You can keep in track to which value is already inserted into array3 using Array of bool, or maybe you had a better method
closed account (367L3TCk)
I'm stuck... can you give me an example ?
1
2
3
4
5
6
7
8
9
//inside while
int min=array1[0];
for(int i=0;i<5;i++)
   if(min>array1[i])
      min=array1[i];
for(int i=0;i<4;i++)
   if(min>array2[i])
      min=array2[i];
array3[k++]=min;


Or just merge both of the array first, then sort it, it much easier

1
2
3
4
5
for(int i=0;i<5;i++)
      array3[k++]=array1[i];
for(int i=0;i<4;i++)
      array3[k++]=array2[i];
//sort array3 
Last edited on
closed account (367L3TCk)
in which while the first one ?
Yup
closed account (367L3TCk)
This is what I did..

//merge sort
i = 0;
j = 0;
while (i < m && j < n)
{
if (array1[i] < array2[j])
{
array3[k] = array1[i];
i++;
}
else
{
array3[k] = array2[j];
j++;
}
k++;

int min=array1[0];


for(int i=0; i < n; i++)
{

if(min > array1[i])
{
min = array2[i];
}
}

for(int i=0; i < m; i++)
{
if(min > array1[i])
{
min = array2[i];
array3[k++] = min;
}}
}
Here's something I whipped up that you can modify if you want. It does pretty much what you asked.

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
	int arr1[] = { 10, 8, 6, 4, 2 };
	int arr2[] = { 9, 7, 5, 3, 1 };

	int arrDest[10];

	for (int i = 0; i < 10; i++)
	{
		i < 5 ? arrDest[i] = arr1[i % 5] : arrDest[i] = arr2[i % 5];
	}

	std::cout << "Merged array: ";

	for (int i = 0; i < 10; i++)
	{
		std::cout << arrDest[i] << ' ';
	}

	for (int j = 0; j < 10; ++j)
	{
		for (int k = j + 1; k < 10; ++k)
		{
			int a;

			if (arrDest[j] > arrDest[k])
			{
				a = arrDest[j];
				arrDest[j] = arrDest[k];
				arrDest[k] = a;
			}
		}
	}

	std::cout << "\n\nSorted array: ";

	for (int i = 0; i < 10; i++)
	{
		std::cout << arrDest[i] << ' ';
	}


Obviously if you changed the array sizes it would break due to me hard coding the sizes. That could be a task for you =D
Last edited on
You need to add some variable or array to not comparing the value that already in the array3, see 3rd post i edt it with easier method and its example
closed account (367L3TCk)
thank you
Topic archived. No new replies allowed.