Search code examples
arrayscsortingbubble-sort

Bubble sort in C


I was trying to implement bubble sort algorithm to sort a 10 element array. I've tried writing the code below and it doesn't seem wrong, but it doesn't sort the elements at all.

Could someone give me a hand?

This is the code:

`

#include <stdio.h>

#define DIM 10

int main() {

    int arr[DIM] = {1, 5, 6, 8, 7, 9, 3, 2, 4, 10};
    int tmp;

    puts("Original array: ");
    for (int i = 0; i < DIM; i++) {
        printf("%3d", arr[i]);
    }
    
    // Bubble sort
    for (int i = 0; i < DIM - 1; ++i) {
        for (int j = 0; j < DIM - i - 1; ++j) {
            // Compare two elements and swap if first > second
            // Use of tmp variable (temporary)
            if (arr[i] > arr[i + 1]) {
                tmp = arr[i];
                arr[i] = arr[i + 1];
                arr[i + 1] = tmp;
            }
        }
    }

    puts("");

    puts("Ascending order arrray: ");
    for (int i = 0; i < DIM; i++) {
        printf("%3d", arr[i]);
    }
    
    puts("");

}

`


Solution

  • Use j in the body of the second loop instead of i.`

        // Bubble sort
    for (int i = 0; i < DIM - 1; ++i) {
        for (int j = 0; j < DIM - i - 1; ++j) {
            // Compare two elements and swap if first > second
            // Use of tmp variable (temporary)
            if (arr[j] > arr[j + 1]) {
                tmp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = tmp;
            }
        }
    }