Bubble Sort

Bubble Sort is a sorting technique which arranges elements in the increasing order by moving across the array and swapping the adjacent elements that are out of order. The complexity of bubble sort is O(n2).

The steps followed are :

• Move from first to the last element of array.
• Swap the element if it is greater than adjacent element.
• No need to swap if adjacent element is greater.

Program

```#include <stdio.h>

void bubble(int [], int);

int main()
{
int arr, n, a, b;
//printf("Enter number of elements\n");
scanf("%d", &n);
//printf("Enter elements of array \n");
printf("Unsorted list is :\t");
for (a = 0; a < n; a++)
{
scanf("%d", &arr[a]);
printf("%d\t",arr[a]);
}
bubble(arr, n);
printf("\nSorted list is:\t");
for ( a = 0 ; a < n ; a++ )
{
printf("%d\t", arr[a]);
}
return 0;
}

void bubble(int array[], int n)
{
int a, b, temp;
for (a = 0 ; a < ( n - 1 ); a++)
{
for (b = 0 ; b < n - a - 1; b++)
{
if (array[b] > array[b+1])
{
temp         = array[b];
array[b]   = array[b+1];
array[b+1] = temp;
}
}
}
}``` Example Consider an Â array with elements 3,7,2,10,1,35,15,5,30,4,8.In order to sort elements,iterations are used.In the first iteration when i=1 sorting is done as given in Â Fig 1 and Fig 2.Refer to Fig 3 and 4 for second iteration i.e i=2,Fig 5 and 6 for i=3.Fig 7 and 8 for i=4,Fig 9 and 10 for i=5.Fig 11 and 12 for i =6 respectively.            Rate this post