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


You are not using bubble sort. this is a selection sort algorithm and your code is not correct. I have updated the code for the bubble sort algorithm.

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

int 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]);
    }

    // bubble Sorting the array
    for (outer = 0; outer < 9; outer++) {
        didSwap = 0;
        for (inner = 0; inner < 9-outer; inner++) {
            //repeatedly swapping the adjacent elements if they are in wrong order
            if (nums[inner] > nums[inner+1]) {
                temp = nums[inner];
                nums[inner] = nums[inner+1];
                nums[inner+1] = 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;
}

3

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