[英]I can't see why Im getting segmentation fault error
我目前正在嘗試學習快速排序,這是我的代碼:
#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;
}
}
代碼運行后,我不斷收到分段錯誤(核心轉儲),我該如何解決這個錯誤。 另外,任何人都可以推薦一個好的 c++ 調試器。 太感謝了
您的QuickSort
function 中有無限遞歸。 每當它被調用時,它都會調用自己,並且沒有條件可以打破循環。
此外,您的swap
function 不起作用。 如其所寫, A
bin 中的值將提供給 function 並解釋為地址。 那不應該編譯。 它編譯的唯一原因是你沒有在你的程序中使用那個 function 。 您正在使用std::swap
因為您已經using namespace std;
,所以不要那樣做。
您的swap
function 應該參考 arguments 並且您需要在QuickSort
function 中添加一個條件。
我不確定您嘗試實施的確切分區方案,因此我做了一些更改以使其符合Hoare 分區方案。
#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';
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.