简体   繁体   中英

Water Jug problem from CLRS

I am reciveing a segmentation fault while running this code.

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

void quicksort(vector<int>&,vector<int>&,int,int);
int partationR(vector<int>&,int,int);
int partationB(vector<int>&,int,int);
int main()
{
vector<int> R = {2,5,3,6,4,8,7,9};
vector<int> B = {8,1,2,5,7,3,6,9};
int p=B[0];
int q=10;
vector<int> RB;
RB.reserve( R.size() + B.size() );
RB.insert( RB.end(), R.begin(), R.end() );
RB.insert( RB.end(), B.begin(), B.end() );

cout<<":::::::::Original::::::::"<<endl;
for(int i=0;i<RB.size();i++)
    cout<<RB[i]<<" ";
cout<<endl;

quicksort(R,B,p,q);

cout<<":::::::::Sorted::::::::::"<<endl;
for(int i=0;i<RB.size();i++)
    cout<<RB[i]<<" ";
cout<<endl;
}

void quicksort(vector<int>& R, vector<int>& B, int p, int q)
{
    int r,s;
        r=partationR(R,p,q);
        s=partationB(B,p,q);
        quicksort(R,B,p,r);
        quicksort(R,B,r+1,q);
        quicksort(R,B,p,s);
        quicksort(R,B,s+1,q);
}

int partationR(vector<int>& R, int p, int q)
{
    int x=R[p];
    int i = 0;
    int j;
    for(j=i+1;j<q;j++)
    {
        if(R[j]<=x)
        {
            i=i+1;
            swap( R[i],R[j] );

        }
    }
    swap( R[i], R[p] );
    return i;
}

int partationB(vector<int>& B, int p, int q)
{
    int y = B[p];
    int k = 0;
    int l;
    for(l=k+1;l<q;l++)
    {
        if (B[k]<=y)
        {
            k=k+1;
            swap( B[k],B[l] );
        }
    }
    swap( B[k],B[p] );
    return k;
}

output of GDB

(gdb) c
Continuing.
:::::::::Original::::::::
2 5 3 6 4 8 7 9 8 1 2 5 7 3 6 9 

Program received signal SIGSEGV, Segmentation fault.
0x00000000004014e6 in std::vector<int, std::allocator<int> >::operator[] (
this=<error reading variable: Cannot access memory at address      0x7fffff7feff8>, 
__n=<error reading variable: Cannot access memory at address     0x7fffff7feff0>)
    at /usr/include/c++/5/bits/stl_vector.h:779
779       operator[](size_type __n) _GLIBCXX_NOEXCEPT
(gdb) kill

There is something strange in your algorithm, you are sorting R and B , and then consider RB as sorted. Probably you wanted to sort RB instead? Or wanted to sort R and B separately and then insert into RB ?

Anyway, segmentation faults usually point to out-of-bound data access, ie in this case, position at which vector element is accessed calculated wrong. One of possible miscalculations:

int p=B[0]; //=8
...
//quicksort(R,B,p,q); -> partationB(B,p,q);
int y = B[p]; // = B[8], however size of B is 8    

Similar happens with q . So, it looks like instead should be just simply:

int p=0;
int q=7;

Because they should be initial indices of vector's partition.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM