Wednesday, April 30, 2025

C Program - How to Implement Bubble Sort in C Programming Language

Bubble sort is a simple sorting algorithm that repeatedly steps through the list of elements to be sorted, compares each adjacent pair of elements and swaps them if they are in the wrong order. This process is repeated multiple times until the entire list is sorted.

The algorithm works by starting at the beginning of the list and comparing the first two elements.

If the first element is greater than the second element, they are swapped. Then the algorithm compares the second and third elements, and so on, until the end of the list is reached. This is considered one pass through the list. After the first pass, the largest element in the list will be in its correct place.

The algorithm then starts again with the first element and performs the same process for the remaining elements until the list is fully sorted.

Bubble sort has a time complexity of O(n^2), which makes it less efficient than other sorting algorithms for larger lists. However, it is easy to understand and implement and can be useful for smaller datasets or as a learning exercise.

//buble sort

#include <stdio.h>

int main()          //temp = generic variable, container
{
    //pairs       1   2  3  4  5  6  7  8  9
    int arr[] = {2, 4, 3, 1, 6, 5, 8, 10, 7, 9};
    int num = 10; //we must know this in advance or calculate it
    int x, y; //for for loops, x, y are just positions where elements exists
    int temp; //used only for swaping, helper container

    for (x = 0; x < num - 1 ; x++)
    {
        for (y = 0; y < num - x - 1  ; y++)
        {
            if(arr[y] > arr[y + 1])
            {
                temp = arr[y];
                arr[y] = arr[y + 1];
                arr[y + 1] = temp;
            }
        }
    }

    //this is just normal printing
    printf("Sorted Array: \n");

    for(x = 0; x < num; x++)
    {
        printf("%d  ", arr[x]);
    }

    return 0;

}

Result: 

Sorted Array:
1  2  3  4  5  6  7  8  9  10
Process returned 0 (0x0)   execution time : 0.035 s
Press any key to continue.

Here's a line-by-line explanation of the Bubble Sort code: 

#include <stdio.h>

This line includes the standard input/output library. 

int main()

This line defines the main function, which is the entry point of the program. 

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

This line creates an integer array of size 10 and initializes it with unsorted values. 

int num = 10;

This line defines a variable to store the size of the array. 

int x, y, temp;

These lines define variables to be used as counters and a temporary variable to store values during swapping. 

for (x = 0; x < num - 1 ; x++)
{
    for (y = 0; y < num - x - 1  ; y++)
    {
        if(arr[y] > arr[y + 1])
        {
            temp = arr[y];
            arr[y] = arr[y + 1];
            arr[y + 1] = temp;
        }
    }
}

These lines of code implement the bubble sort algorithm.

The algorithm compares adjacent elements in an array and swaps them if they are in the wrong order. It repeats this process for each pair of adjacent elements until no more swaps are required.

The outer loop in this code iterates through the array from the first element (index 0) to the second to last element (index num-2). The inner loop iterates through the array from the first element (index 0) to the second to last element minus the number of iterations performed in the outer loop (index num-x-2).

The reason for this is that, after each iteration of the outer loop, the largest element is guaranteed to be in its correct position at the end of the array, so there is no need to compare it with any elements after that position.

Within the inner loop, the code compares the current element at index y with the next element at index y+1.

If the current element is greater than the next element, it means they are in the wrong order, and the code swaps them by assigning the value of the current element to a temporary variable, assigning the value of the next element to the current element, and assigning the value of the temporary variable to the next element.

After both loops complete, the array is sorted in ascending order. 

printf("Sorted Array: \n");
for(x = 0; x < num; x++)
{
    printf("%d  ", arr[x]);
}

These lines print out the sorted array. 

return 0;

This line indicates the end of the main function and returns a value of zero to the operating system to indicate that the program executed successfully.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...