jeudi 31 décembre 2020

Simple Bubble sort program. It works flawlessly about 85% of times but in some cases it doesn't sort the list

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

main()
{
    int ctr, inner, outer, didSwap, temp;
    int nums[10];
    time_t t;

    srand(time(&t));

    for (ctr = 0; ctr < 10; ctr++)
    {
        nums[ctr] = (rand() % 99) + 1;
    }

    printf("\nHere is the list before the sort:\n");
    for (ctr = 0; ctr < 10; ctr++)
    {
        printf("%3d",nums[ctr]);
    }

    // Sorting the array

    for (outer = 0; outer < 9; outer++)
    {
        didSwap = 0;

        for (inner = outer + 1; inner < 10; inner++)
        {
            if (nums[inner] < nums[outer])
            {
                temp = nums[inner];
                nums[inner] = nums[outer];
                nums[outer] = temp;
                didSwap = 1;
            }
        }

        if (didSwap == 0)
        {
            break;
        }
    }

    printf("\n\nHere is the list after sorting:\n");
    for (ctr = 0; ctr < 10; ctr++)
    {
        printf("%3d", nums[ctr]);
    }

    printf("\n");

    return 0;
}

Sometimes it doesn't sort the list properly and sometimes doesn't sort at all. Screenshot of error




Aucun commentaire:

Enregistrer un commentaire