我对泡泡排序很好奇,所以我创建了一个接受用户输入的函数,而不是将值存储在数组的位置,但它会不断打印出一些垃圾值。
#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 */
答案 0 :(得分:1)
我遇到的错误我正在尝试打印数组中的第一个值,如果您没有0
数字,则该值始终为10
:
printf("%d\n", number[0]);
应该阅读
printf("%d\n", number[9]);
并且我想要放置值的循环将它们放在错误的位置,所以我就这样固定了
for (int i=0; i<10; i++)
{
number[i] = input % 10;
input /= 10;
}
这就是我改变的一切,它运作良好。
答案 1 :(得分:0)
您的号码输入代码有点时髦。而不是输入一个长数字然后使用%10来获取每个数字的值,为什么不输入一组10个数字呢?
for (int i=0; i<10;i++)
{
scanf_s("%d", &input);
number[i]=input;
}
答案 2 :(得分:0)
冒泡排序应
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;
}
}