Written by Sai Sandeep Thota on December 19, 2012 in C > Programming

Bubble Sort using C with Explanation

GET ALERTS:

Get our Latest updates delivered to your mailbox!

Bubble sort program is used to sort elements in ascending order, It is based on comparison method. An element is picked first and is compared with the other elements present in the list. If any element less than the selected element is found then it is swapped accordingly. Bubble sort is advantageous if we have a small list of elements, It takes more time if there are many elements. We have written an easy bubble sort code in C programming below.

Its time complexity is O(n) in Best case and O(n²) in Average and Worst cases. Take a look at the simple program below.

/*  C Program to Implement Bubble Sort */
#include<conio.h>
#include<stdio.h>
#define max 5
void bubblesort(int, int[]);

void bubblesort(int size, int data[])
{
	int i, j, temp;
	printf("\nSorted Order is:\n");
	for(i=1;i<=size-1;i++)
	{
		for(j=i+1;j<=size;j++)
		{
			if(data[i]>data[j])
			{
				temp=data[i];
				data[i]=data[j];
				data[j]=temp;
			}

		}

	}
	for(i=1;i<=size;i++)
		printf("%d\t",data[i]);
}

void main()
{
	int i, size, data[max];
	clrscr();
	printf("\nEnter no of Elements:");
	scanf("%d",&size);
	printf("\nEnter Elements:");
	for(i=1;i<=size;i++)
		scanf("%d",&data[i]);
	printf("\nUnsorted data:\n");
	for(i=1;i<=size;i++)
		printf("%d\t",data[i]);
	bubblesort(size, data);
	getch();
}

Output:
bubble-sort-output

{ 0 comments… add one now }

Leave a Comment

Previous post:

Next post: