C Program to Implement Bubble Sort

1. Introduction

Bubble Sort is one of the simplest sorting algorithms. It works by repeatedly swapping adjacent elements if they are in the wrong order. The algorithm gets its name because smaller elements "bubble" to the top of the list with each iteration of the outer loop.

2. Program Overview

In this program, we will:

1. Create a function that implements the Bubble Sort algorithm.

2. Sort an array of integers using the Bubble Sort algorithm.

3. Display the sorted array.

3. Code Program

#include <stdio.h>

// Function to swap two numbers
void swap(int *xp, int *yp) {
    int temp = *xp;
    *xp = *yp;
    *yp = temp;
}

// Bubble Sort function
void bubbleSort(int arr[], int n) {
    int i, j;
    for (i = 0; i < n-1; i++)
        for (j = 0; j < n-i-1; j++)
            if (arr[j] > arr[j+1])
                swap(&arr[j], &arr[j+1]);
}

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

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

    bubbleSort(arr, n);

    printf("Sorted array: \n");
    printArray(arr, n);
    return 0;
}

Output:

Original array:
64 34 25 12 22 11 90
Sorted array:
11 12 22 25 34 64 90

4. Step By Step Explanation

1. We begin with a swap function that, given two integer pointers, swaps the values they point to.

2. The bubbleSort function takes in an array and its size. It then iterates over the array multiple times, each time comparing adjacent elements and swapping them if they are in the wrong order.

3. As the algorithm progresses, the largest unsorted element will always "bubble up" to its correct position at the end of the array. This guarantees that the array is sorted after n-1 passes.

4. The printArray function is a simple utility function to display the elements of an array.

5. The main function demonstrates how to use the bubbleSort function. We first print the original unsorted array, then apply bubble sort, and finally print the sorted array.

It's worth noting that while Bubble Sort is simple and easy to implement, it's not the most efficient sorting algorithm for large datasets.

Comments