Kol*_*olt 0 c++ sorting exception
我试着写一个countingsort,但它有一些问题.
这是代码:
int *countSort(int* start, int* end, int maxvalue)
{
int *B = new int[(int)(end-start)];
int *C = new int[maxvalue];
for (int i = 0; i < maxvalue; i++)
{
*(C+i) = 0;
}
for (int *i = start; i < end; i++)
{
*(C+*i) += 1;
}
for (int i = 1; i < maxvalue-1 ; i++)
{
*(C+i) += *(C+i-1);
}
for (int *i = end-1; i > start-1; i--)
{
*(B+*(C+(*i))) = *i;
*(C+(*i)) -= 1;
}
return B;
}
Run Code Online (Sandbox Code Playgroud)
在最后一个循环中,它抛出一个异常"Acces违规写入位置:-some ram address-"
我哪里做错了?
for (int i = 1; i < maxvalue-1 ; i++)
Run Code Online (Sandbox Code Playgroud)
这是不正确的上限.你想从去1到maxvalue.
for (int *i = end-1; i > start-1; i--)
{
*(B+*(C+(*i))) = *i;
*(C+(*i)) -= 1;
}
Run Code Online (Sandbox Code Playgroud)
这个循环也完全不正确.我不知道它做了什么,但是一个简短的心理测试表明,第一次迭代将数组中最后一个元素的值的索引处的B元素设置为它显示的次数.我保证这不正确.最后一个循环应该是这样的:
int* out = B;
int j=0;
for (int i = 0; i < maxvalue; i++) { //for each value
for(j<C[i]; j++) { //for the number of times its in the source
*out = i; //add it to the output
++out; //in the next open slot
}
}
Run Code Online (Sandbox Code Playgroud)
最后一点,你为什么要玩这样的指针?
*(B + i) //is the same as
B[i] //and people will hate you less
*(B+*(C+(*i))) //is the same as
B[C[*i]]
Run Code Online (Sandbox Code Playgroud)