C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Arrays in C

Bubble Sort Program

C Program: Bubble Sort Program

C

#include <stdio.h>

 

int main() {

    int arr[100], n, i, j, temp;

 

    // Input number of elements

    printf("Enter number of elements: ");

    scanf("%d", &n);

 

    // Input array elements

    printf("Enter %d elements:\n", n);

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

        scanf("%d", &arr[i]);

    }

 

    // Bubble Sort algorithm

    for(i = 0; i < n - 1; i++) {

        for(j = 0; j < n - i - 1; j++) {

            if(arr[j] > arr[j + 1]) {

                // Swap elements

                temp = arr[j];

                arr[j] = arr[j + 1];

                arr[j + 1] = temp;

            }

        }

    }

 

    // Display sorted array

    printf("\nSorted array in ascending order:\n");

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

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

    }

 

    printf("\n");

    return 0;

}

Output

 
INPUT :
Enter number of elements: 6
Enter 6 elements:
23 12 45 9 56 10

OUTPUT :
Sorted array in ascending order:
9 10 12 23 45 56

Explanation

  1. Bubble Sort repeatedly compares adjacent elements and swaps them if they are in the wrong order.
  2. After each outer loop iteration, the largest element “bubbles up” to its correct position at the end of the array.
  3. The process repeats until the array is completely sorted.

Algorithm Steps

  1. Start from the first element.
  2. Compare the current element with the next one.
  3. If the current element is greater, swap them.
  4. Continue until the end of the array.
  5. Repeat the process for all elements except the already sorted ones.