冒泡排序问题与升序

时间:2014-02-21 16:32:59

标签: c sorting bubble-sort

我这里有一个程序,要求用户输入最多20个数字。然后显示输入的数字,删除重复项,然后使用冒泡排序按升序显示它们,并删除重复项。我的问题在于泡沫排序。当它按升序列出nos时,最后一个数字总是被删除。有人可以通过展示它为什么这样做来帮助我。

#include <stdio.h>    

/* This program asks the user to enter up to 20 numbers. It then displays the numbers entered, removes duplicates
 and then list the numbers with the duplicates removed in ascending order.
 */
int main (void)
{
    setbuf(stdout, NULL);

    int nums[20] , i , j, k, swap ;
    int count=0;

    {
        printf("Enter integers. (Negative -1 to stop):\n");
        for (i=0; i < 20; i++)
        {
            scanf("%d", &nums[i]);
            count = count +1;

            if(nums[i] == -1 ) // If user enters -1 stops the program from expecting anymore number inputs
                break;
        }
    }

    printf("The numbers you entered are:\n"); // outputs the numbers you entered one number per line
    for(i=0;i<count;++i)
    {
        printf("%d\n", nums[i]);
    }

    printf("\n Your numbers with the duplicate numbers removed:\n ");
    // for loop for removing the duplicate numbers that the user enters.
    for(i=0;i<count;i++)
    {
        for(j=i+1;j<count;)
        {
            if(nums[j]==nums[i])
            {
                for(k=j;k<count-1;++k)
                {
                    nums[k]=nums[k+1];
                }
                count--;
            }
            else
            {
                j++;
            }
        }
    }

    for(i=0;i<count;i++) // outputs the numbers you entered with the duplicates removed one number per line
        printf("%d\n ",nums[i]);

    // start of the bubble sort for listing the numbers in ascending order. Can replace ">" with "<" to list in descending order
    for(i=0; i<(k-1); i++)
    {
        for(j=0; j < k - i; j++)
        {
            if (nums[j] > nums[j+1])
            {
                swap = nums[j];
                nums[j] =nums[j+1];
                nums[j+1] = swap;
            }
        }
    }
    printf("\nYour numbers sorted in to ascending order with the duplicates removed:\n");

    for(j=0;j<i;j++) // outputs the numbers in ascending order. One number per line
        printf("%d\n ",nums[j]);


    return 0;
}

3 个答案:

答案 0 :(得分:0)

替换

 for(i=0; i<(k-1); i++)
 {
     for(j=0; j < k - i; j++)

 for(i=0; i<k; i++)
 {
     for(j=0; j < k - i-1; j++)

for(i=0; i<=(k-1); i++)
{
     for(j=0; j < k - i-1; j++)

答案 1 :(得分:0)

您的排序例程使用k作为条件。上面的代码表明,根据您拥有的数据,k可能会或可能不会正确初始化。您可能想使用count

最后一个循环相同。

一个建议:永远不要重复使用循环变量,它会吸引各种各样的麻烦。您的代码很难阅读,可能还有一些问题。

P.S。您可以在以{开头的每个块中声明一个变量。在循环中声明变量以防止不必要的重用。

答案 2 :(得分:0)

有两个问题。

请注意,删除重复项后,您的变量count中的条目总数。

这样做更容易

for(i=0; i < count - 1; i++)
{
    for(j=0; j < count - 1 - i; j++)
    {
        .....

注意第二个循环中的-1。这可以防止迭代超出范围,因为您使用的是j+1

第二个错误只是在您的打印循环中。

由于您已经在count中存储了要打印的数字,因此请更改

for(j = 0; j < i; j++)

for(j = 0; j < count; j++)
相关问题