[英]bubble sort printing garbage values
我對氣泡排序感到很好奇,所以我做了一個函數,它接受用戶輸入,然后將值存儲在數組的正數中,但它會不斷打印出一些垃圾值。
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
void sort(int*z);
void swap(int* element1Ptr,int* element2Ptr);
int main(void)
{
int number[10];
int input;
int* sorting;
sorting = number;
printf("Please enter a number less than 10 digits long");
scanf_s("%d", &input);
for (int i=0; i<10;i++)
{
number[9-i]=input%10;
input/=10;
}
printf("\n");
sort(sorting);
printf("%d\n",number[0]);
}
氣泡請求代碼錯誤還是傳遞錯誤的變量?
void sort(int* z)
{
int pass; /* pass counter */
int j; /* comparison counter */
/* loop to control passes */
for ( pass = 0; pass < 11; pass++ )
{
/* loop to control comparisons during each pass */
for ( j = 0; j < 10; j++ )
{
/* swap adjacent elements if they are out of order */
if ( z[ j ] > z[ j + 1 ] )
{
swap( &z[ j ], &z[ j + 1 ] );
} /* end if */
} /* end inner for */
} /* end outer for */
}/* end function bubbleSort */
void swap(int* element1Ptr,int* element2Ptr)
{
int hold = *element1Ptr;
*element1Ptr = *element2Ptr;
*element2Ptr = hold;
} /* end function swap */
我嘗試打印數組中的第一個值時遇到的錯誤,如果您沒有10
位數字,則該值將始終為0
:
printf("%d\n", number[0]);
應該讀
printf("%d\n", number[9]);
而我大膽地將值放入的循環將它們放在錯誤的位置,因此我將其固定為
for (int i=0; i<10; i++)
{
number[i] = input % 10;
input /= 10;
}
那就是我所做的全部更改,並且效果很好。
您的數字輸入代碼有點時髦。 為何不輸入單個長數字,然后使用%10獲取每個數字的值,為什么不輸入一組10個數字呢?
for (int i=0; i<10;i++)
{
scanf_s("%d", &input);
number[i]=input;
}
氣泡排序應為
for ( pass = array_length - 2; pass >= 0; pass-- )
{
for ( j = 0; j <= pass; j++ )
{
compare_and_swap(& z[j], & z[j + 1]);
}
// at this point in the code, you are guaranteed that
// every element beyond the index of pass is in the final
// correct location in the array
// so if you input array was {9, 8, 7, 6, 5}
// and pass = 2
// then elements 3 and 4 are correct here:
// {*, *, *, 8, 9}
}
void compare_and_swap(int* a, int* b)
{
if (*a > *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.