# C Programming (Turbo C++ Compiler) - Sorting Algorithm - Bubble Sort

We often using sorting algorithm to sort numbers and strings. Also we have many sorting algorithms. I have explained here on how bubble sort algorithm works. Look at the yellow color high lighting section on output to understand how algorithm works after each iteration.

The complete program and test run output are given below:

## Source Code

#include <stdio.h>
#include <conio.h>

int BubbleSort()

{

int max;

int *numarray = 0;
int i,j,k;
int temp;

printf(
"\nProgram for Ascending order of Numeric Values using BUBBLE SORT");

printf("\n\nEnter the total number of elements: ");

scanf("%d", &max);

numarray = (int*) malloc(int * max);

for(i = 0; i < max; i++)

{

printf("\nEnter [%d] element: ", i + 1 );

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

}

printf("Before Sorting   : ");

for(k = 0; k < max; k++)

printf("%d ", numarray[k]);

printf("\n");

for(i = 1; i < max; i++)

{

for(j = 0; j < max - i; j++)

{

if(numarray[j] > numarray[j + 1])

{

temp = numarray[j];

numarray[j] = numarray[j + 1];

numarray[j + 1] = temp;

}

}

printf("After iteration %d": ", i);

for(k = 0; k < max; k++)

printf("%d ", numarray[k]);

printf(
"/*** %d biggest number(s) is(are) pushed to the end of the array ***/\n", i + 1);

}

printf("\n\nThe numbers in ascending orders are given below:\n\n");

for(int i = 0; i < max; i++)

{

printf("Sorted [%d] element: ",i + 1);

printf("%d\n", numarray[i]);

}

free(numarray);

return 0;

}

int main()

{

BubbleSort();

return 0;

}

## Output

Program for Ascending order of Numeric Values using BUBBLE SORT

Enter the total number of elements: 8

Enter  element: 80

Enter  element: 60

Enter  element: 40

Enter  element: 20

Enter  element: 10

Enter  element: 30

Enter  element: 50

Enter  element: 70

Before Sorting   : 80 60 40 20 10 30 50 70

After iteration 1: 60 40 20 10 30 50 70 80

After iteration 2: 40 20 10 30 50 60 70 80

After iteration 3: 20 10 30 40 50 60 70 80

After iteration 4: 10 20 30 40 50 60 70 80

After iteration 5: 10 20 30 40 50 60 70 80

After iteration 6: 10 20 30 40 50 60 70 80

After iteration 7: 10 20 30 40 50 60 70 80

The numbers in ascending orders are given below:

Sorted  element: 10

Sorted  element: 20

Sorted  element: 30

Sorted  element: 40

Sorted  element: 50

Sorted  element: 60

Sorted  element: 70

Sorted  element: 80