2

我对冒泡排序很好奇,所以我创建了一个函数,它接受用户输入并将值存储在数组的位置中,但它不断打印出一些垃圾值。

#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 */  
4

3 回答 3

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;
}

这就是我改变的一切,它工作得很好。

于 2013-09-20T03:23:30.767 回答
0

你的数字输入代码有点时髦。与其输入一个长数字,然后使用 %10 来获取每个数字的值,不如输入一组 10 个数字?

for (int i=0; i<10;i++)
{
    scanf_s("%d", &input);
    number[i]=input;
}
于 2013-09-20T03:33:58.923 回答
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;
    }
}
于 2013-09-20T04:58:11.240 回答