c - 升序冒泡排序问题

标签 c sorting bubble-sort

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

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

最佳答案

有两个问题。

请记住,删除重复项后,您的变量 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++)

关于c - 升序冒泡排序问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21939910/

相关文章:

python - python 中的冒泡排序帮助 - 升序和降序

c - 冒泡排序中的用户输入

java - 冒泡排序不起作用

c - 格式化输出和 fprintf

android - 优化 NEON 装配功能

c - 如何从结构页中获取关联数据的物理地址?

javascript - 如何根据 javascript 或 jquery 中的 highcharts 的 x,y 对中的日期对数组进行排序

java - 对从文件中读取的数组进行排序

无法将字符串分配给数组

javascript - 在 IE 中排序数组