【发布时间】:2014-02-21 16:32:59
【问题描述】:
我有一个程序要求用户输入最多 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;
}
【问题讨论】:
-
在发布到全世界之前,请正确缩进您的代码。此处不使用 TAB 帮助。
-
在您提交之前,您可能需要查看您的冒泡排序算法,因为这个。 不是。如果乱序,常规冒泡排序会沿着顺序交换 adjacent 对。到达终点时,最大值为“冒泡”。下一次通过停止索引减一。重要提示:如果 any 传递执行 no 实际交换,您可以停止排序。 IE。预排序列表是最佳情况 O(n)。你错过了提前退出。
标签: c sorting bubble-sort