C Program for Bubble Sorting

In this example, the bubbleSort function takes an array and its size as parameters, and uses nested loops to iterate through the array and swap adjacent elements that are out of order.

The main() function initializes an array, calls bubbleSort to sort it, and prints the sorted array.
Program :
#include <stdio.h>

void bubbleSort(int arr[], int n) {
    int i, j, temp;
    for (i = 0; i < n - 1; i++) {      
        // Last i elements are already in place  
        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;
            }
        }
    }
}

int main() {
    int arr[] = {5, 3, 8, 4, 2};
    int n = sizeof(arr)/sizeof(arr[0]);
    int i;

    printf("Unsorted array: ");
    for (i = 0; i < n; i++)
        printf("%d ", arr[i]);

    bubbleSort(arr, n);

    printf("\nSorted array: ");
    for (i = 0; i < n; i++)
        printf("%d ", arr[i]);
    printf("\n");
    return 0;
}
Output :
Unsorted array: 5 3 8 4 2 
Sorted array: 2 3 4 5 8 


Example 2 : Implementing bubble sort algorithm in a C program :

Program :
#include<stdio.h>

int main(){

   int count, temp, i, j, number[30];

   printf("How many numbers are you going to enter?: ");
   scanf("%d",&count);

   printf("Enter %d numbers: ",count);

   for(i=0;i<count;i++)
   scanf("%d",&number[i]);

   /* This is the main logic of bubble sort algorithm 
    */
   for(i=count-2;i>=0;i--){
      for(j=0;j<=i;j++){
        if(number[j]>number[j+1]){
           temp=number[j];
           number[j]=number[j+1];
           number[j+1]=temp;
        }
      }
   }

   printf("Sorted elements: ");
   for(i=0;i<count;i++)
      printf(" %d",number[i]);

   return 0;
}
Output :
How many numbers are you going to enter?: 5
Enter 5 numbers: 12
5
28
37
17
Sorted elements:  5 12 17 28 37