Write a C program to sort an array using bubble sort

Description: Take 5 numbers in an array and sort them in ascending order.

Hint:

  • Compare each pair of neighbours. If the left one is bigger, swap them. Repeat this until the array is sorted.

C program for bubble sort

#include <stdio.h>

int main(void) {
    int a[5], temp;

    printf("Enter 5 numbers: ");
    for (int i = 0; i < 5; i++) {
        scanf("%d", &a[i]);
    }

    for (int i = 0; i < 4; i++) {
        for (int j = 0; j < 4 - i; j++) {
            if (a[j] > a[j + 1]) {
                temp = a[j];
                a[j] = a[j + 1];
                a[j + 1] = temp;
            }
        }
    }

    printf("Sorted array: ");
    for (int i = 0; i < 5; i++) {
        printf("%d ", a[i]);
    }
    printf("\n");
    return 0;
}

Output:

Output of the above program is

Enter 5 numbers: 64
25
12
22
11
Sorted array: 11 12 22 25 64

How it works

  • After the first pass of the outer loop, the biggest number (64) has moved to the end. After the second pass, the second biggest is in its place, and so on.
  • The inner loop runs 4 - i times, because the last i elements are already sorted.

Learn more about the similar topics:
Tutorials
C Arrays
C Two Dimensional Arrays
C Passing Arrays to Functions
C Strings
C String Input and Output
C String Functions
C strlen() Function
Exercises & Assignments
Write a C program to find the sum and average of array elements
Write a C program to find the largest element in an array
Write a C program to print the elements of an array in reverse order
Write a C program to sort an array using bubble sort
Write a C program to search an element in an array
Write a C program to add two matrices
Write a C program to find the length of a string without using strlen
Interview Questions & Answers
What is an array in C?
How is a string stored in C?
How to reverse a string in C?
What is the difference between memcpy() and strcpy() in C?