所以我正在实施快速排序,一旦我启动程序就会出错。我认为从逻辑上讲,一切都应该没问题。我认为问题出在交换函数内,因为如果我将其注释掉,它不会崩溃。
#include <iostream>
using namespace std;
void swap1(int& x, int& y)
{
int tmp = x;
x = y;
y = x;
}
int partition(int arr[], int cof, int length)
{
int x = arr[length];
int j = cof -1;
for(int i = cof; length-1; i++ )
{
if(arr[i] <= x)
{
i++;
swap1(arr[i], arr[j]);
}
swap1(arr[i+1], arr[length]);
}
return j++;
}
void quick_sort(int arr[], int cof, int length)
{
if(cof < length)
{
int q = partition(arr, cof, length);
quick_sort(arr,cof, q-1);
quick_sort(arr,q+1, length);
}
}
int main()
{
int arr[]={1, 3, 2, 5, 4};
quick_sort(arr, 1, 5);
for(int i = 0; i < 5; i++)
{
cout << arr[i] << endl;
}
return 0;
}