# Bubble Sort using C

Bubble sort is one of the most popular sorting methods. It can be treated as a selection sort because it is based on successively selecting the smallest element, second smallest element and so on. In order to find the successive smallest elements this process relies heavily on the exchange of the adjacent elements and swaps them if they are in the wrong order.

Bubble sort has worst-case and average complexity both О(n2), where n is the number of items being sorted.

The complete source code

```/*
* File:   BubbleSort.c
* Author: https://www.roytuts.com
*/

#include <stdio.h>
#include <stdlib.h>

void bubbleSort(int a[], int n) {
int i, j, k;
int temp;
for (i = 0; i < n; i++) {
j = n - 1;
k = 0;
while (j > i) {
if (a[j] < a[j - 1]) {
temp = a[j];
a[j] = a[j - 1];
a[j - 1] = temp;
k = 1;
}
j--;
}
if (k == 0) {
break;
}
}
printf("\n");
printf("\nThe sorted array elements are given below\n");
for (i = 0; i < n; i++) {
printf("a[%d]=%d ", i, a[i]);
}
}

int main() {
int i, n = 6;
int a[] = {15, 8, 17, 12, 38, 19};
printf("\n:: Bubble Sort ::\n");
printf("\nInput array elements\n");
for (i = 0; i < n; i++) {
printf("a[%d]=%d ", i, a[i]);
}
bubbleSort(a, n);
}```

Output

```:: Bubble Sort ::

Input array elements
a[0]=15 a[1]=8 a[2]=17 a[3]=12 a[4]=38 a[5]=19

The sorted array elements are given below
a[0]=8 a[1]=12 a[2]=15 a[3]=17 a[4]=19 a[5]=38```

Thanks for reading.

## Soumitra Roy Sarkar

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on JEE Tutorials Twitter Facebook  Google Plus Linkedin Or Email Me