Sep 14, 2015 at 2:00am Sep 14, 2015 at 2:00am UTC
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 Sep 14, 2015 at 4:39pm Sep 14, 2015 at 4:39pm UTC
Sep 14, 2015 at 2:42am Sep 14, 2015 at 2:42am UTC
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
Sep 14, 2015 at 2:45am Sep 14, 2015 at 2:45am UTC
I'm stuck... can you give me an example ?
Sep 14, 2015 at 2:54am Sep 14, 2015 at 2:54am UTC
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 Sep 14, 2015 at 3:09am Sep 14, 2015 at 3:09am UTC
Sep 14, 2015 at 2:59am Sep 14, 2015 at 2:59am UTC
in which while the first one ?
Sep 14, 2015 at 3:10am Sep 14, 2015 at 3:10am UTC
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;
}}
}
Sep 14, 2015 at 3:22am Sep 14, 2015 at 3:22am UTC
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 Sep 14, 2015 at 3:23am Sep 14, 2015 at 3:23am UTC
Sep 14, 2015 at 3:24am Sep 14, 2015 at 3:24am UTC
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