Reputation: 23
Hello I'm trying to get my program to arrange numbers into ascending order.
It first list the numbers you enter(up to 20) it then removes any duplicates and list them. Then I need them to get listed in ascending ordering using a bubble sort. Can anyone help me with that last part?
#include <stdio.h>
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 )
break;
}
}
printf("The numbers you entered are:\n");
for(i=0;i<count;++i)
{
printf("%d\n", nums[i]);
}
printf("\n Your numbers with the duplicate numbers removed:\n ");
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++)
printf("%d\n ",nums[i]);
for(i=0; i<(k-1); i++)
{
for(i=0; i < k-j; i++)
{
if (nums[i] > nums[i+1])
{
swap = nums[i];
nums[i] =nums[i+1];
nums[i+1] = swap;
}
}
}
printf("\n Your numbers sorted in to ascending order:\n");
for(j=0;j<i;j++)
printf("%d\n ",nums[i]);
return 0;
}
Thanks!
Upvotes: 0
Views: 189
Reputation: 25347
Your bubble sort in the code is:
for(i=0; i<(k-1); i++)
{
for(i=0; i < k-j; i++)
{
}
if (nums[i] > nums[i+1])
{
swap = nums[i];
nums[i] =nums[i+1];
nums[i+1] = swap;
}
}
Assuming k
is the number of elements to sort, it should be:
for(i=0; i<(k-1); i++)
{
for(j=0; j < k - 1 - i; j++)
{
if (nums[j] > nums[j+1])
{
swap = nums[j];
nums[j] =nums[j+1];
nums[j+1] = swap;
}
}
Your code had the second loop with an empty body and you need a diffrent loop variable for the inner loop than i
, since this is driving the outer loop.
Upvotes: 1
Reputation: 3162
Bubble sort part
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;
}
}
}
Upvotes: 0