我正在學習 dsa,我嘗試在 c 中實作基數排序。我使用了 programiz 的本教程。 我實作了它,但是他們使用的數字陣列得到了正確排序,但是當我使用不同的陣列時,它顯示了一些垃圾值。
當我插入這個
int array[] = {121, 432, 564, 23, 1, 45, 788};
輸出是“1 23 45 121 432 564 788”輸出
但是當我插入這個
int array[] = {3,4,1,5,2};
輸出為“1 2 3 4 2496”
輸出
我實作了教程中的代碼。誰能指出問題
#include <stdio.h>
void radix_sort(int array[], int size);
void counting_sort(int array[], int size, int place);
int main(void)
{
int array[] = {3,4,1,5,2};
int size = sizeof(array) / sizeof(int);
radix_sort(array, size);
for (int i = 0; i < size; i )
printf("%i ", array[i]);
printf("\n");
}
void radix_sort(int array[], int size)
{
int max = array[0];
for (int i = 1; i < size; i )
{
if (array[i] > max)
max = array[i];
}
for (int place = 1; max / place > 0; place *= 10)
counting_sort(array, size, place);
}
void counting_sort(int array[], int size, int place)
{
int output[size 1];
int max = (array[0] / place) % 10;
for (int i = 1; i < size; i )
{
if (((array[i] / place) % 10) > max)
max = array[i];
}
int count[max 1];
for (int i = 0; i < max; i)
count[i] = 0;
for (int i = 0; i < size; i )
count[(array[i] / place) % 10] ;
for (int i = 1; i < 10; i )
count[i] = count[i - 1];
for (int i = size-1; i >= 0; i--)
{
output[count[(array[i] / place) % 10] - 1] = array[i];
count[(array[i] / place) % 10]--;
}
for (int i = 0; i < size; i )
array[i] = output[i];
}
uj5u.com熱心網友回復:
for (int i = 1; i < 10; i ) {count[max 1]自=>以來將越界訪問陣列, count[5 1]因此您的程式具有未定義的行為。它可能會崩潰或輸出垃圾或做任何事情。
您應該i <= max在該回圈中使用:
for (int i = 1; i <= max; i ) // use `i <= max` here
count[i] = count[i - 1];
您還需要將可變長度陣列的記憶體清零,count因為它在創建后將包含不確定的值。您嘗試這樣做,for (int i = 0; i < max; i) count[i] = 0;但錯過了陣列中的最后一個元素。你也需要i <= max那里:
int count[max 1];
for (int i = 0; i <= max; i) count[i] = 0;
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/474638.html
上一篇:停留/折疊導航欄
