Search code examples
calgorithmbubble-sort

Why my bubble sort implementation prints an extra numbers?


Ok so im trying to implement bubble sort but it does not work properly when I type in 0's as a number. It displays extra numbers.

int main ()
{
    int amount;
    int numbers[50];
    int x, y, z, j;
    int swap;

    printf("How many numbers do you want to sort: ");
    scanf("%i", &amount);

    for (x = 0; x <= amount; x++) 
    {
        printf("Enter number %i: ", x);
        scanf("%i", &numbers[x]);
    }

    for (j = 0; j <= amount; j++) 
    {
        for (y = 0; y <= amount; y++) 
        {
            if (numbers[y] > numbers[y + 1]) 
            {
                swap = numbers[y];
                numbers[y] = numbers[y + 1];
                numbers[y + 1] = swap;
            }       
        }
    }


    for (z = 0; z <= amount; z++) {
        printf("%i ", numbers[z]);
    }
    return 0;
}

Solution

  • If you start your for loops with 0, x = 0; x <= amount; will give you an extra loop.

    ie:

    amount = 5,
    loop: 0, 1, 2, 3, 4, 5 (total 6 times)
    

    Try x = 0; x < amount; instead

    amount = 5
    loop: 0, 1, 2, 3, 4 (total 5 times)
    

    And one more thing, you need to check where your y is in the loop later on:

    numbers[y + 1] = swap;
    

    as [y+1] will cause out of bounds error when it's the last iteration of the loop. Remember, arrays we typically start counting from 0, and the last element is therefore size-1.

    If you loop from y = 0; y < amount; you'll get:

    numbers[0], numbers[1], numbers[2]. numbers[3], numbers[4], total 5 elements
    

    So your last loop with numbers[y + 1] will actually try to access numbers[5], a theoretical 6th element which doesn't exist. Suggest to set that loop to y < amount-1