[英]c++ counting sort
我試圖寫一個計數排序,但是有一些問題。
這是代碼:
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;
}
在最后一個循環中,它引發異常“在位置寫訪問沖突:-some ram address-”
我哪里做錯了?
for (int i = 1; i < maxvalue-1 ; i++)
那是不正確的上限。 您想要從1
變為maxvalue
。
for (int *i = end-1; i > start-1; i--)
{
*(B+*(C+(*i))) = *i;
*(C+(*i)) -= 1;
}
此循環也完全不正確。 我不知道它的作用,但是簡短的心理測試表明,第一次迭代將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
}
}
最后要說明的是,為什么要使用這樣的指針?
*(B + i) //is the same as
B[i] //and people will hate you less
*(B+*(C+(*i))) //is the same as
B[C[*i]]
由於無論如何都在使用C ++,為什么不通過使用std::vector
而不是動態分配的數組(並在過程中泄漏一個)來(劇烈地)簡化代碼?
std::vector<int>countSort(int* start, int* end, int maxvalue)
{
std::vector<int> B(end-start);
std::vector<int> C(maxvalue);
for (int *i = start; i < end; i++)
++C[*i];
// etc.
除此之外,您使用的邏輯對我來說毫無意義。 我認為要獲得工作結果,最好是坐在一張紙上並確定需要使用的步驟。 我將計數部分留在了上面,因為我認為很多事情是正確的。 我不認為其余的確實是。 我什至會給出一個非常簡單的提示:完成計數后,您可以僅基於C
內容生成B
(您的結果), 而根本不需要引用原始數組。 最簡單的方法通常是使用嵌套循環。 還要注意,在B
reserve
空間並使用push_back
將數據放入其中可能比設置其初始大小更容易。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.