在做我的 C 編程練習時,我遇到了這個奇怪的問題:合并排序和快速排序演算法無限回圈遍歷我的結構陣列,試圖對其進行排序。
現在,有第三種排序演算法可用:插入排序。有了這個,排序作業正常。
所以,我在做這個練習之前測驗了所有 3 種演算法,它們作業正常(嘗試使用 int、double、strings 和 array of strings...)。
我不知道...有什么建議嗎?
這是歸并排序的代碼:
void upo_merge_sort(void *base, size_t n, size_t size, upo_sort_comparator_t cmp)
{
assert(base != NULL);
upo_merge_sort_rec(base, 0, n-1, size, cmp);
}
void upo_merge_sort_rec(void *base, size_t lo, size_t hi, size_t size, upo_sort_comparator_t cmp)
{
if(lo >= hi) { return; }
size_t mid = lo (hi - lo) / 2;
upo_merge_sort_rec(base, 0, mid, size, cmp);
upo_merge_sort_rec(base, mid 1, hi, size, cmp);
upo_merge_sort_merge(base, lo, mid, hi, size, cmp);
}
void upo_merge_sort_merge(void *base, size_t lo, size_t mid, size_t hi, size_t size, upo_sort_comparator_t cmp)
{
unsigned char *ptr = base;
unsigned char *aux = NULL;
size_t n = hi - lo 1;
size_t i = 0;
size_t j = mid 1 - lo;
size_t k;
aux = malloc(n*size);
if(aux == NULL) {
perror("Unable to allocate memory for auxiliary vector");
abort();
}
memcpy(aux, ptr lo*size, n*size);
for(k = lo; k <= hi; k) {
if(i > (mid - lo)) {
memcpy(ptr k*size, aux j*size, size);
j;
}
else if(j > (hi - lo)) {
memcpy(ptr k*size, aux i*size, size);
i;
}
else if(cmp(aux j*size, aux i*size) < 0) {
memcpy(ptr k*size, aux j*size, size);
j;
}
else {
memcpy(ptr k*size, aux i*size, size);
i;
}
}
free(aux);
}
并比較功能:
int by_track_number_comparator(const void *a, const void *b)
{
const entry_t *aa = a;
const entry_t *bb = b;
int diff = aa->track_num - bb->track_num;
return diff;
}
int by_track_title_comparator(const void *a, const void *b)
{
const entry_t *aa = a;
const entry_t *bb = b;
return strcmp(aa->track_title, bb->track_title);
}
entry_t 是結構型別。
uj5u.com熱心網友回復:
有一個簡單的錯誤upo_merge_sort_rec使函式遞回得比它需要的要深得多。它應該將元素從索引排序lo到hi包含,但是遞回呼叫之一的較低索引錯誤地使用了固定的較低索引 0:
upo_merge_sort_rec(base, 0, mid, size, cmp);
應該:
upo_merge_sort_rec(base, lo, mid, size, cmp);
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/380759.html
上一篇:計算給定字串出現次數的函式
下一篇:帶回傳值的樹遍歷函式
