Search code examples
c++recursionsegmentation-faultquicksort

double recursion segmentation fault c++


I've recently written this quicksort sorting algorithm. After compiling I get a "segmentation fault (core dumped)". I debugged it and it turned out that line 25 causes the problem: v2 = quicksort(v2); However, I do not know why I get a the "core dumped", as I have no idea what's the problem with this line. Here's my code:

#include <iostream>
#include <vector>
#include <random>

using namespace std;

vector <float> quicksort(vector <float> Vec)
{
    if(Vec.size() > 1)
    {
        float pivot = Vec[(Vec.size())/2-1];

        vector <float> v1, v2;
        vector <float> V;

        for(unsigned int i = 0; i < Vec.size(); i++)
        {
            if(Vec[i] >= pivot)
                v2.push_back(Vec[i]);
            else
                v1.push_back(Vec[i]);
        }

        v1 = quicksort(v1);
        v2 = quicksort(v2);
        //after debuggung, I found out that the line above causes the "segmentation fault (core dumped)" (line 25)

        for(unsigned int i = 0; i < v1.size(); i++)
            V.push_back(v1[i]);
        for(unsigned int i = 0; i < v2.size(); i++)
            V.push_back(v2[i]);

        return V;
    }
    else
    {
        return Vec;
    }

}

int main()
{
    ios_base::sync_with_stdio(0);
    cin.tie(0);

    vector <float> v;

    for(int i = 0; i < 100; i++)
    {
        v.push_back(rand() % 100);
        cout << v[i] << " ";
    }

    v = quicksort(v);

    for(int i = 0; i < 100; i++)
    {
        cout << v[i] << " ";
    }

    return 0;
}

Thanks for the help.


Solution

  • First of all, to get a totally random number using rand() you need to seed the number generator. To do this you include the "time.h" library and then write: srand (time(NULL));

    Secondly, your quicksort takes two parameters, a vector named Vec and an int f, that isn't used for anything. Take int f of the function's parameters.

    Thirdly, the problem is that an infinite loop is happening in this part of the code (lines 17 to 23):

    for(unsigned int i = 0; i < Vec.size(); i++){
        if(Vec[i] >= pivot)
            v2.push_back(Vec[i]);
        else
            v1.push_back(Vec[i]);
    }
    

    Imagine that our Vec vector is {2, 3} (this were the actual values, because we didn't seed the random number generation).

    What's happening is that we have our pivot = 2, and then we are saying that if Vec[0], which is 2, is bigger or equal than the pivot, we add Vec[0] to v2, and then the same for Vec[1], which is 3. Then this loops infinitely, because then you say v2 = quicksort(v2);. That will make Vec = v2. And that means that it will never get smaller, because, again, Vec is {2, 3}, and therefore our pivot = 2.