- 我正在研究冒泡排序,但長度完全關閉,開始列印垃圾值,如 0,1,2
- 我試過在我的 for 回圈中操作我的條件,但它仍然輸出垃圾值
void bubbleSort(int array[], int len){
int temp;
int counter = -1;
printf("\n");
while(counter != 0){
counter = 0;
for (int i = 0; i < len; i ) {
//compare two ints swich the greater value to the right
if (array[i] > array[i 1]){
temp = array[i 1];
array[i 1] = array[i];
array[i] = temp;
counter ;
//increment counter
}
}
}
for (int i = 0; i <= len; i ) {
printf("%i ", array[i]);
}
printf("\nBubble Sort Completed\n");
}
int main(void){
int a[] = {1, 2, 4, 5, 7 ,6, 8, 3, 9};
int b[] = {10, 20, 40, 54, 23, 23, 12};
size_t a_length = sizeof(sizeof(a)/sizeof(a[0]));
size_t b_length = sizeof(sizeof(b)/sizeof(b[0]));
bubbleSort(a, a_length);
bubbleSort(b, b_length);
}
我的輸出通常是這樣的
1 2 3 4 5 6 7 8 9 冒泡排序完成
0 1 10 12 20 23 23 40 54 冒泡排序完成
- 也只是有點好奇為什么陣列 b 的長度等于 8?值不應該是7嗎?
uj5u.com熱心網友回復:
至少有這些問題:
比較最終訪問陣列邊界之外,array[i 1]導致未定義行為(UB)。UB 可能會發生任何事情。
// Alternative code
// for (int i = 0; i < len; i ) {
for (int i = 1; i < len; i ) {
// if (array[i] > array[i 1]){
if (array[i-1] > array[i]){
temp = array[i];
array[i] = array[i-1];
array[i-1] = temp;
counter ;
}
}
... 和 ...
// for (int i = 0; i <= len; i ) {
for (int i = 0; i < len; i ) {
printf("%i ", array[i]);
}
......和...... @Weather Vane
尺寸計算錯誤。
//size_t a_length = sizeof(sizeof(a)/sizeof(a[0]));
//size_t b_length = sizeof(sizeof(b)/sizeof(b[0]));
size_t a_length = sizeof a / sizeof a[0];
size_t b_length = sizeof b / sizeof b[0];
還可以考慮在陣列索引中使用相同的型別
// void bubbleSort(int array[], int len){
void bubbleSort(int array[], size_t len){
size_t temp, counter;
...
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/322585.html
上一篇:使用strtok()和strtod()從c中的命令列中分離9個型別為double的數字
下一篇:分段默認值(雙指標/結構)
