C program for bubble sort: To sort the given array in the ascending or descending order using one of the simple sorting technique.

Bubble sort technique
What is bubble sort? The main idea behind the bubble sort algorithm is to compare the adjacent elements repeatedly and swap their positions if they were in the wrong order.
In this technique we compare the first element with preceding element if the number next to that is small then we perform swapping so that the smaller number become a first, Then again go for next preceding number this process will continue till end of iteration and we perform N number of iteration to a sorting element, at last, we will get sorted list.

Bubble sort algorithm in c

  1. Declare variables. a[], N
  2. Take numbers input from user. a[N]
  3. Traverse the array till end
    For i = 0 to N
    Compare adjacent elements till end
    For j =0 to end
    If a[j] > a[j+1]
    Swap a[j] and a[j+1]
    else
    Continue
  4. Print sorted array. a[]

C program for Bubble sort

#include <stdio.h>

int main()
{
int array[100], n, c, d, swap;

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

printf("Enter %d integers\n", n);

for (c = 0; c < n; c++)
scanf("%d", &array[c]);

for (c = 0 ; c < n - 1; c++)
{
for (d = 0 ; d < n - c - 1; d++)
{
if (array[d] > array[d+1]) /* For decreasing order use < */
{
swap = array[d];
array[d] = array[d+1];
array[d+1] = swap;
}
}
}

printf("Sorted list in ascending order:\n");

for (c = 0; c < n; c++)
printf("%d\n", array[c]);

return 0;
}

Output :

C program for bubble sort

Write A Comment