Implementing Bubble Sort program in C with Algorithm

Bubble Sort program in C with Algorithm - Blurnooz.com

(A) Bubble Sort :-         

Algorithm: BUBBLE_SORT(list,n)

Step 1: [Initialization]
	i <- 0
Step 2: [Repeat]
	While (i<n-1) repeat through Step 7
Step 3: [Initialization]
	j <- 0
Step 4: [Repeat]
	While (j<n-i-1) repeat through Step 6 
Step 5: [Exchange]
        if(list[j]>list[j+1])
	then
	temp <- list[j]
	list[j] <- list[j+1]
	list[j+1] <- temp
Step 6: [Increment j]
	j <- j+1
Step 7: [Increment i]
	i <- i+1
Step 8: [Finished]
	Exit

 

Program :-

#include
#include
void bubble_sort(int [],int);
void main()
{
	int i,n,a[10];
	clrscr();
	printf("Enter no of element:");
	scanf("%d",&n);
	printf("Enter elements:\n");
	for(i=0;i<n;i++)
	{
		printf("Element %d:",i);
		scanf("%d",&a[i]);
	}
	bubble_sort(a,n);
	printf("\nArray after sorting:\n");
	for(i=0;i<n;i++)
	{
		printf("%d",a[i]);
		if(i<n-1)
		{
		printf(",");
		}
		else
		{
		printf(".");
		}
	}
	getch();
}
void bubble_sort(int a[],int n)
{
	int i,j,temp;
	for(i=0;i<n-1;i++)
	{
		for(j=0;j<n-i-1;j++) { if(a[j]>a[j+1])
			{
				temp=a[j];
				a[j]=a[j+1];
				a[j+1]=temp;
			}
		}
	}
}

Output :-

Enter no of element:5
Enter elements:
Element 0:3
Element 1:7
Element 2:1
Element 3:25
Element 4:14

Array after sorting:
1,3,7,14,25.

Leave a Reply

Please enter your comment!
Please enter your name here

*