Bubble Sort in C Programming

In this source code example, we will write a code to implement the Bubble Sort algorithm in the C programming language.

Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order.

In this C program, we will take input from the User or console. 

Bubble Sort in C Programming

We will write a C program to sort N numbers in ascending order using the Bubble Sort algorithm:
#include<stdio.h>

void Bubblesort(int[], int);

void main() {
	int x[20], i, n;
	printf("\n Enter the no of element to be sorted:");
	scanf("%d", &n);
	printf("\n Enter %d elements:", n);
	for (i = 0; i < n; i++)
		scanf("%d", &x[i]);
	Bubblesort(x, n);
	printf("\n The sorted array is:\n");
	for (i = 0; i < n; i++)
		printf("%4d", x[i]);
}
void Bubblesort(int a[], int n) {
	int temp, pass, i;
	for (pass = 0; pass < n - 1; pass++) {
		for (i = 0; i < n - pass - 1; i++) {
			if (a[i] > a[i + 1]) {
				temp = a[i];
				a[i] = a[i + 1];
				a[i + 1] = temp;
			}
		}
	}
}

Output:


 Enter the no of element to be sorted:5

 Enter 5 elements:60
40
30
20
10

 The sorted array is:
  10  20  30  40  60

Related Algorithms in C Programming


Comments