Header-C
Header-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.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

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

error

Enjoy this blog? Please spread the word :)