开发者

bottom up mergesort

i have following code for bottom up mergesort it does it's operation on file m-by-m merges doubles m on each pass here is code

#include <iostream>
#include <vector>
using namespace std;

inline int Min(int a,int b)
{
    return a<b?a:b;
}

void merge(int a[],int l,int m,int r)
{
    vector<int>b;
    int i, j;
    for (i=m+1;i>=l;i--)  b[i-1]=a[i-1];
    for (j=m;j<r;j++) b[r+m-j]=a[j+1];
    for (int k=l;k<=r;k++)
        if ( b[j]<b[i]) 
            a[k]=b[j--];  
        else
            a[k]=b[i++];
}

void mergesort(int a[],int l,int r)
{
    for (int m=1;m<=r-l;m=m+m)
        for (int i=l;i<=r-m;i+=m+m)
            merge(a,i,i+m-1,Min(i+m+m-1,r));
}

int main()
{
    int a[]={12,4,7,3,9,8,10,11,6};
    int n=sizeof(a)/sizeof(int);
    mergesort(a,0,n-1);
    for (int i=0;i<n;i++)
    {
        cout<<a[i]<< "  ";
    }

    return 0;
}

but when i run this code there is 开发者_运维知识库exception which says that vector's out of range error was occured please help


You have not initialised your vector to have any data in it.

I guess this is an exercise which is why you are reinventing the wheel. I am not sure that is an excuse for using single-character identifiers which makes your code hard to understand.

If a is an array and l is its length you can initialise b with

vector<int> b( a, a+l );

Presumably you are creating a temporary clone of your array for the purpose of the sort.

Isn't mergesort recursive, by the way? I don't see yours being.

I have other issues with your code too, eg your indentation suggests that the for loops are nested but the semi-colons after the statements that are on the same line as the for statements suggest otherwise. I'd suggest you always use braces on your loops.


In function merge you have vector<int>b; b is of size 0 here. You should rezise() your vector, or initialize it with the array:

vector<int> v(arr, arr+size);


You create b as an empty vector, and then start addressing its elements. It has size 0, so that's invalid. You should give it a larger size.


Others have addressed your problem with trying to index elements in an empty vector. In addition, the following loop has a problem:

for (i=m+1;i>=l;i--)  b[i-1]=a[i-1];

The last iteration through the loop has i=l and you address the [i-1] element of the vector/array. When l=0 this is the index -1 and will be out-of-range for both the vector and array.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜