简体   繁体   中英

I can't see why Im getting segmentation fault error

I'm currently trying to learn Quick Sort, and here is my code:

#include<iostream>
#include<vector>
#include<cmath>
using namespace std;
void swap(int *a, int *b)
{
    int t = *a;
    *a = *b;
    *b = t;
}

int partition(vector<int> &A, int low, int high)
{
    int pivot = A[low];
    int i = low; 
    int j = high;
    while(i < j){
        do
        {
            i++;
        }while(A[i]>=pivot);
        do
        {
            j--;
        }while(A[j]<pivot);
        if(i < j)
        {
            swap(A[i], A[j]);
        }
    }
    swap(A[low], A[j]);
    return j;
}

void QuickSort(vector<int> &A, int low, int high)
{
    int j = partition(A, low, high);
    QuickSort(A, low, j);
    QuickSort(A, j+1, high);
}

int main()
{
    vector<int> A{-7, 11, -3, 3, 2};

    QuickSort(A, 0, A.size()-1);
    for(int i:A)
    {
        cout << i << endl;  
    }
}

after the code ran, I keep getting Segmentation fault (core dumped), how do I fix this error. also, could any one recommend a good c++ debugger. thank you so much

You have infinite recursion in your QuickSort function. Whenever it gets called, it'll call itself and there is no condition there to break the cycle.

Also, your swap function does not work. As it is written, the values in the A bins will be supplied to the function and interpreted as addresses. That should not compile. The only reason why it does compile is that you don't use that function in your program. You are using std::swap because you've done using namespace std; , so don't do that.

Your swap function should take the arguments by reference and you need to add a condition in the QuickSort function.

I wasn't sure exactly which partitioning scheme you tried implementing so I made some changes to make it work in accordance with the Hoare partition scheme .

#include <iostream>
#include <vector>

void swap(int& a, int& b) {                    // take arguments by reference
    int t = a;
    a = b;
    b = t;
}

size_t partition(std::vector<int>& A, size_t low, size_t high) {
    int pivot = A[(high + low) / 2];
    size_t i = low;
    size_t j = high;
    while(true) {
        while(A[i] < pivot) ++i;
        while(A[j] > pivot) --j;
        if(i >= j) return j;
        swap(A[i], A[j]);
        ++i;
        --j;
    }
}

void QuickSort(std::vector<int>& A, size_t low, size_t high) {
    if(low < high) {                         // added condition
        size_t j = partition(A, low, high);
        QuickSort(A, low, j);
        QuickSort(A, j + 1, high);
    }
}

int main() {
    std::vector<int> A{-7, 11, -3, 3, 2};

    QuickSort(A, 0, A.size() - 1);
    for(int i : A) {
        std::cout << i << '\n';
    }
}

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