Bubble Sort Algorithm in C

 

 

Program Overview

The Bubble Sort algorithm is a simple sorting technique that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. The process is repeated until the list is sorted. This algorithm is called “Bubble Sort” because smaller elements “bubble” to the top of the list.

Program Structure


#include <stdio.h>

void bubbleSort(int arr[], int n) {
    int i, j, temp;
    // Traverse through all elements in the array
    for (i = 0; i < n - 1; i++) {
        // Last i elements are already sorted
        for (j = 0; j < n - i - 1; j++) {
            // Swap if the element found is greater than the next element
            if (arr[j] > arr[j + 1]) {
                temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
}

void printArray(int arr[], int size) {
    int i;
    for (i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }
    printf("\\n");
}

int main() {
    int arr[] = {64, 34, 25, 12, 22, 11, 90};
    int n = sizeof(arr) / sizeof(arr[0]);
    
    printf("Unsorted array: \\n");
    printArray(arr, n);
    
    bubbleSort(arr, n);
    
    printf("Sorted array: \\n");
    printArray(arr, n);
    return 0;
}

Documentation

  • Function void bubbleSort(int arr[], int n):This function implements the Bubble Sort algorithm. It takes an integer array arr and its size n as parameters. It sorts the array in ascending order.
  • Function void printArray(int arr[], int size):This function prints the elements of the array. It takes an integer array arr and its size size as parameters.
  • Function int main():This is the entry point of the program. It initializes an array, calls the sorting function, and prints the results before and after sorting.

Conclusion

The Bubble Sort algorithm, while not the most efficient for large datasets, is an excellent introduction to sorting algorithms due to its simplicity. This implementation in C demonstrates the fundamental structure of sorting algorithms and how to manipulate arrays.

 

Leave a Reply

Your email address will not be published. Required fields are marked *