Sort an Array in Ascending Order Using Bubble Sort in C

This program sorts the elements of a 1-D array in ascending order using the bubble sort technique.

C Program

#include <stdio.h>

int main() {
    int arr[100], n, i, j, temp;

    printf("Enter number of elements: ");
    scanf("%d", &n);

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

    for (i = 0; i < n - 1; i++) {
        for (j = 0; j < n - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }

    printf("Sorted array (ascending): ");
    for (i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");

    return 0;
}

Explanation

  • Bubble sort repeatedly compares adjacent elements and swaps them if they're in the wrong order, causing the largest unsorted element to "bubble up" to its correct position each pass.
  • The outer loop runs n - 1 passes; the inner loop shrinks by one each pass (n - i - 1) since the last i elements are already sorted after each pass.
  • A temp variable is needed to swap two array elements without losing either value.

Sample Output

Enter number of elements: 5
Enter 5 elements:
5 2 9 1 5
Sorted array (ascending): 1 2 5 5 9

Leave a Comment