Atilla Gun
Atilla Gun

Reputation: 15

I tried make a bubble sort with C but it's not working (It's doing bubble sort 10 times)

first i giving how many numbers will i enter then i enter numbers. he need make bubble sort to them but its writing like======> 1 3 2 6 = 0 0 0 0(but it must be like 1 2 3 6(small to big))

the app how i want=

7

1 5 2 7 4 7 3

1 2 3 4 5 7 7

#include<stdio.h>
int main()
{
    int numbers[500000];
    int counter=0;
    int howmany;

    scanf("%d",&howmany);//getting how many numbers will we enter
    int howmany2=howmany;//we will use this for write all numbers after all

    while(howmany>0)//getting all numbers
    {
        scanf("%d",&numbers[counter]);
        howmany--;
        counter++;
    }

    int checker1,checker2;//its gonna check first and second number, then second and third...etc
    int hm=howmany-1;//its gonna check entered number-1 times(1,2,3)={1,2},{2,3}
    int clone1;//later we will copy numbers[checker1]
    int tentime=10;//we gonna do bubble sort 10 times

    while(tentime>0)//doing bubble sort
    {
        checker1=0;
        checker2=1;

        while(hm>0)
        {
            if(numbers[checker1]>numbers[checker2])
            {
                clone1=numbers[checker1];
                numbers[checker1]=numbers[checker2];
                numbers[checker2]=clone1;
            }

            checker1++;
            checker2++;
            hm--;
        }

    tentime--;
    }

    int counter2=0;

    while(howmany2>0)//showing new number sort on screen
    {
        printf("%d ",numbers[counter]);
        howmany2--;
        counter2++;
    }

    printf("\n");
    return 0;
}

Upvotes: 0

Views: 52

Answers (1)

jmq
jmq

Reputation: 1591

You have several problems in your code:

  • At the end of your first while loop howmany will be 0. As a result hm will be set to -1 and the sort loop (while hm > 0 ) will never run.
  • When you print out the results are using counter as the array index (this is 4 which is out of bounds and never changes since you are incrementing counter2. As a result you are printing out an undefined value (0 in your case) four times.
  • Declaring an array of size 500000 may blow up your stack. Even if not it is way larger than you need

Upvotes: 1

Related Questions