5areductase
5areductase

Reputation: 269

Bubble sort in C not sorting

I'm trying to generate 10 random numbers and sort them. But they're not getting sorted.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

main()

{
int c, d, swapped, temp;
int numb[10];
time_t t;

srand(time(&t));

for (c=0; c<10; c++)
{
    numb[c] = (rand() % 100) + 1;
}

printf("Before sorting:");
for (c=0; c<10; c++){
    printf("%d\n", numb[c]);
}

for (c=0; c<10; c++)
{
    swapped = 0;
    for (d=0; d < 9 - c; d++)
    {
        if (numb[d] > numb[d+1])
        {
            temp = numb[d];
            numb[d] = numb[d+1];
            numb[d] = temp;
            swapped = 1;
        }
    }
    if (swapped == 0)
    {
        break;
    }

}

printf("\nAfter sorting:\n");
for (c=0; c<10; c++)
{
    printf("%d\n", numb[c]);
}

return 0;
}

I can't seem to figure out why this sort isn't working. In fact, it simply regurgitates the same list. Can someone point out where I made a mistake?

Upvotes: 2

Views: 74

Answers (1)

Ed Heal
Ed Heal

Reputation: 59997

You code for swapping is incorrect: This code

temp = numb[d];
numb[d] = numb[d+1];
numb[d] = temp;
swapped = 1;

Should be

temp = numb[d];
numb[d] = numb[d+1];
numb[d+1] = temp;
swapped = 1;

Upvotes: 4

Related Questions