Tuesday, 22 August 2023

Write program in c to implement Bubble Sort.

Bubble Sort Algorithm in C

Bubble Sort Algorithm in C

This code demonstrates the Bubble Sort algorithm in C.


#include <stdio.h>

int main()
{
    int n;

    printf("Enter Array Size::");
    scanf("%d", &n);

    int ar[n];

    printf("Enter %d elements::", n);
    for (int i = 0; i < n; i++)
    {
        scanf("%d", &ar[i]);
    }

    int count = 1;
    while (count < n)
    {
        for (int i = 0; i < n - count; i++)
        {
            if (ar[i] > ar[i + 1])
            {
                int temp = ar[i];
                ar[i] = ar[i + 1];
                ar[i + 1] = temp;
            }
        }
        count++;
    }

    printf("\\nSorted Elements::");
    for (int i = 0; i < n; i++)
    {
        printf("%d ", ar[i]);
    }

    return 0;
}
    

This code implements the Bubble Sort algorithm to sort an array of integers. The algorithm repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order.

Feel free to experiment with this code and understand how the Bubble Sort algorithm works!

1 comment:

  1. Output:

    Enter Array Size::5

    Enter 5 elements::56 45 12 36 54

    Sorted Elements::

    12 36 45 54 56

    ReplyDelete

Interactive Report: Introduction to the Internet of Things (IoT) ...

Popular Posts