Friday 18 October 2024

Bubble Sort

#include <stdio.h>


int main() {

    int A[5] = {64, 34, 25, 12, 22}; // Initialize the array

    int i, j, x;


    // Sorting the array using Bubble Sort 

    for (i = 0; i < 4; i++) { // Iterate through the array, up to the second last element

        for (j = 0; j < 4 - i; j++) { // Adjusted inner loop to ensure proper comparisons

            if (A[j] > A[j + 1]) { // Compare adjacent elements

                // Swap elements A[j] and A[j + 1]

                x = A[j];

                A[j] = A[j + 1];

                A[j + 1] = x;

            }

        }

    }


    // Display the sorted array

    printf("After Sorting: ");

    for (i = 0; i < 5; i++) {

        printf("%d ", A[i]);

    }

    printf("\n");


    return 0;

}