Bubble Sort Programs in C


Levels of difficulty: / perform operation:

Program 1

C program to sort an array using Bubble Sort Algorithm.

  
#include <stdio.h>
#include <conio.h>
void main()
{
	int a[15],i,j,n,temp;
	clrscr();
	printf("\nENTER THE SIZE OF ARRAY:")  ;
	scanf("%d",&n);
	printf("\nENTER VALUES FOR THE ARRAY:\n");
	for(i=0;i<n;i++)
		scanf("%d",&a[i]);
	for(i=0;i<n-1;i++)
	{
		for(j=i+1;j<n;j++)
		{
			if(a[i]>a[j])
			{
				temp=a[i];
				a[i]=a[j];
				a[j]=temp;
			}
		}
	}
	printf("\nTHE SORTED ARRAY IS:\n");
	for(i=0;i<n;i++)
		printf("%d ",a[i]);
	getch();
}


Output



Program 2

Program will sort the name strings using Bubble Sort technique.

  
#include <stdio.h>
#include <conio.h>
#include <string.h>
 
void main()
{
	char name[10][8], Tname[10][8], temp[8];
	int i, j, N;
 
	clrscr();
 
	printf("Enter the value of N\n");
	scanf("%d", &N);
 
	printf("Enter %d names\n", N);
	for(i=0; i< N ; i++)
	{
		scanf("%s",name[i]);
		strcpy (Tname[i], name[i]);
	}
 
	for(i=0; i < N-1 ; i++)
	{
		for(j=i+1; j< N; j++)
		{
			if(strcmpi(name[i],name[j]) > 0)
			{
				strcpy(temp,name[i]);
				strcpy(name[i],name[j]);
				strcpy(name[j],temp);
			}
		}
	}
 
	printf("\n----------------------------------------\n");
	printf("Input Names\tSorted names\n");
	printf("------------------------------------------\n");
	for(i=0; i< N ; i++)
	{
		printf("%s\t\t%s\n",Tname[i], name[i]);
	}
	printf("------------------------------------------\n");
	getch();
} 


Output