Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
222 views
in Technique[技术] by (71.8m points)

c - 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("
Here is the list before the sort:
");
    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("

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

    printf("
");

    return 0;
}

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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("
Here is the list before the sort:
");
    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("

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

    return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...