我正在尝试制作一个简单的快速排序算法,每当我运行它时,它都会引发一个我无法调试的异常。错误显示“Final.exe 中 0x00D01367 处的未处理异常:0xC0000005:访问冲突写入位置 0x00000000。” 我不能使用s[i] = value;
并且应该使用s.push_back(value);
吗?我以前使用过前者,没有任何问题,所以我现在不知道为什么会出错。
#include <iostream>
#include <vector>
#include <list>
#include <cassert>
using namespace std;
typedef unsigned int uint;
uint partition(uint low, uint high, vector<double> & s)
{
uint i; //first index for partitioning
uint j; //second index for partitioning
uint pivotpoint; //index of the partition
double pivotvalue; //value at the pivot
double swapvalue; //placeholder variable for the swap
pivotvalue = s[low];
j = low;
for (i = (low+1); i<=high; i++)
{
if (s[i] < pivotvalue)
{
j++;
swapvalue = s[i];
s[i] = s[j];
s[j] = swapvalue;
}
}
pivotpoint = j;
swapvalue = s[low];
s[low] = s[pivotpoint];
s[pivotpoint] = swapvalue;
return pivotpoint;
}
void quicksort(uint low, uint high, vector<double> & s)
{
uint pivotpoint;
if(high>low)
{
pivotpoint = partition(low,high,s);
if(pivotpoint != 0)
{
quicksort(low, pivotpoint-1, s);
}
if(pivotpoint != high)
{
quicksort(pivotpoint+1,high, s);
}
}
}
int main( /*int argc, char* argv[] */)
{/*
if( argc != 2 )
{
cout << "Usage: ./filename.txt" << endl;
cout << "filename.txt should be a file with the items to be sorted" << endl;
exit( 2 );
}
assert(argc == 2)
{
}
*/
vector<double> s;
s[0] = 1.1;
s[1] = 2.4;
s[2] = 7.1;
s[3] = 5.4;
s[4] = 2.5;
s[5] = 1.2;
s[6] = 0.9;
quicksort(0,s.size(),s);
for(uint i = 0; i<s.size(); i++)
{cout << s[i] << endl;}
return 0;
}