Tuesday, December 18, 2012

Bubble sort algorithm in c

Bubble sort 

void shuffle(int numbers[], int arraySize);
void bubbleSort(int numbers[], int arraySize);
 
int main(void) {
 
    int numbers[30];
 
    int i;
 
    for(i = 0; i < 30; i++) {
        numbers[i] = i+1;
    }
 
    shuffle(numbers, 30);
 
    printf("Shuffled numbers\n");
    for(i=0; i < 30; i++) {
        printf("%d ", numbers[i]);
    }
 
    bubbleSort(numbers, 30);
 
    printf("\nSorted numbers\n");
    for(i=0; i < 30; i++) {
        printf("%d ", numbers[i]);
    }
 
    return EXIT_SUCCESS;
}
 
/*
 * This shuffle logic is inefficient.
 * just for test
 * */
void shuffle(int numbers[], int arraySize) {
    int randomIndex1, randomIndex2;
    int i, tmp;
 
    for(i= 0; i < arraySize; i++) {
        randomIndex1 = rand() % arraySize;
        randomIndex2 = rand() % arraySize;
        tmp = numbers[randomIndex1];
        numbers[randomIndex1] = numbers[randomIndex2];
        numbers[randomIndex2] = tmp;
    }
}
 
void bubbleSort(int numbers[], int arraySize) {
    int i, j, tmp;
    /*
     * Two types of sorting loop.
     * try either one.
     * */
 
    /*for( i = (arraySize - 1); i > 0 ; i --) {
        for(j=1; j<=i ; j++) {
            if(numbers[j-1] > numbers[j] ) {
                tmp = numbers[j-1];
                numbers[j-1] = numbers[j];
                numbers[j] = tmp;
            }
        }
    }*/
 
    for(i = 0 ; i < arraySize ; i++) {
        for(j=1; j < arraySize-i; j++) {
            if(numbers[j-1] > numbers[j]) {
                tmp = numbers[j-1];
                numbers[j-1] = numbers[j];
                numbers[j] = tmp;
            }
        }
    }
}
 
Shuffled numbers
1 24 26 23 30 9 12 8 6 15 5 19 13 14 20 16 17 4 28 27 21 29 7 18 3 22 25 2 10 11 
Sorted numbers
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30

The bubbleSort function sorts the array in ascending order using the Bubble Sort algorithm.

Algorithm Description:
Nested Loops:

The outer loop runs for the total number of elements (arraySize).
The inner loop compares adjacent elements and swaps them if they are out of order.
Key Mechanism:
In each iteration of the outer loop, the largest unsorted element "bubbles up" to its correct position at the end of the array.

Optimization:
The inner loop's range decreases with each outer loop iteration (arraySize - i) because the last elements are already sorted.

Alternative Implementation:
The commented-out code block demonstrates another way to implement Bubble Sort by iterating backward in the outer loop. Both approaches achieve the same result.