-
September 11th, 2009, 01:49 PM
#1
What am i doing wrong here.
Last edited by versacestl; September 11th, 2009 at 05:17 PM.
-
September 11th, 2009, 02:36 PM
#2
Re: What am i doing wrong here.
Aren't you missing a less than sign in the if condition of merge_sort?
Code:
if (p < r)
{
//...
}
-
September 11th, 2009, 02:38 PM
#3
Re: What am i doing wrong here.
Originally Posted by ltcmelo
Aren't you missing a less than sign in the if condition of merge_sort?
Code:
if (p < r)
{
//...
}
yep sorry.. changed some variables.. code is how i have it currently..
still getting same issue..
-
September 11th, 2009, 03:31 PM
#4
Re: What am i doing wrong here.
I found some errors on your implementation. Here's a fixed version, but you should check if there are still other errors. Hope you understand the notes in the code.
Code:
#include <algorithm>
#include <iostream>
void merge(int a[], int p, int q, int r)
{
//Changed initialization to use q.[/color]
int i = q + 1;
int j = q;
//Changed initialization to p instead of 0.
int k = p;
//What exactly is this for?
//int n = ((p- r) + 1);
//int b[] = {n};
int b[10]; //Size of 10 just for the example.
if (p < r)
{
//And this?
//b[n] = a[n];
//You need to fill b accordingly. Perhaps that's what you were trying with the parts I didn't understand?
for (; i > p; --i)
b[i-1] = a[i-1];
for (; j < r; ++j)
b[r+q-j] = a[j+1];
for (; k <= r; k++)
{
if ((i > q) || (j <= r&& b[j] <= b[i]))
{
a[k] = b[j];
j = j - 1; //Subtract.
}
else
{
a[k] = b[i];
i = i + 1;
}
}
}
}
void merge_sort(int a[], int p, int r)
{
if (p < r)
{
int q= ((p+ r) / 2);
merge_sort(a, p, q);
merge_sort(a, q+ 1, r); //r not q here.
merge(a, p, q, r);
}
}
int main()
{
int v[] = {4, 7, 2, 1, 8, 6, 3, 5, 9, 0};
merge_sort(v, 0, 9);
std::copy(v, v + 10, std::ostream_iterator<int>(std::cout, " "));
return 0;
}
Last edited by ltcmelo; September 11th, 2009 at 05:29 PM.
Reason: Added more comments
-
September 11th, 2009, 03:54 PM
#5
Re: What am i doing wrong here.
Is that working for you? Cause it's still blowing up for me
-
September 11th, 2009, 05:40 PM
#6
Re: What am i doing wrong here.
Originally Posted by versacestl
Is that working for you? Cause it's still blowing up for me
Yes, it does. I get the sorted output.
In general, you should keep the original post even if it's been solved because it might help other people going through the same problem.
Last edited by ltcmelo; September 11th, 2009 at 05:42 PM.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|