# Bubble Sort Algorithm

Bubble Sort Algorithm is the important topic of the Data structure. Moreover, Freestudy9 has all kind of important topic and information about the subject.

**Bubble sort**sometimes referred as**sinking sort.**- It is a simple sorting algorithm that works by repeatedly stepping through the list to sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order.
- Moreover, The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted.
- The algorithm gets its name from the way smaller elements “bubble” to the top of the list.
- Also, As it only uses comparisons to operate on elements, it is a comparison sort.
- Although the algorithm simple, it is too slow for practical use, even compared to insertion sort.

**Algorithm for Bubble Sort**

for i ← 1 to *n* do

for* j* ← 1 to *n-i* do

If Array[*j*]>Array[j+1] then

*/* For decreasing order use */* temp ← Array[*j*]

Array[j] ← A [j+1]

Array[j+1] ← temp

**Program **

#include<stdio.h>

void main()

{

int array[100], n, i, j, temp;

printf(“Enter number of elements\n”);

scanf(“%d”, &n);

printf(“Enter %d integers\n”, n);

for (i = 0; I<n; i++)

{

scanf(“%d”, &array[i]);

}

for (i = 0 ;i<(n-1);i++)

{

for (j = 0 ; j<n – c – 1; j++)

{

if (array[j]>array[j+1]) */* For decreasing order use*/*

{

temp = array[j];

array[j] = array[j+1];

array[j+1] = temp;

}

}

}

printf(“Sorted list in ascending order:\n”); for (i = 0 ;i<n ;i++ )

{

printf(“%d\n”, array[i]);

}

getch();

}

**Example of Bubble Sort Algorithm**

Consider an array A of 5 element

**Pass-1: Also, The comparisons for pass-1 are as follows.**

Compare A[0] and A[1]. Since 45>34, interchange them.

Compare A[1] and A[2]. Since 45<56, no interchange.

Compare A[2] and A[3]. Since 56>23, interchange them.

Compare A[3] and A[4]. Since 56>12 interchanges them.

Also, At the end of the first pass the largest element of the array, 56, is bubbled up to the last position in the array as shown.

**Pass-2: The comparisons for pass-2 are as follows.**

Compare A[0] and A[1]. Since 34<45, no interchange.

Compare A[1] and A[2]. Since 45>23, interchange them.

Compare A[2] and A[3]. Since 45>12, interchange them.

**Pass-3: Moreover, The comparisons for pass-3 are as follows.**

Compare A[0] and A[1]. Since 34>23, interchange them.

Compare A[1] and A[2]. Since 34>12, interchange them.

**Pass-4: The comparisons for pass-4 are as follows.**

Compare A[0] and A[1]. Since 23>12, interchange them.

**Related** **Terms**

Data Structure, Indexing File Management, Clustering Indexes, Engineering Study.

## Leave a Reply