Bubble Sort

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

void bubble(int a[], int n);

int main(void)
{
	int *a;
	int i,n;
	clrscr();
	printf("\t\t\t------------\n");
	printf("\t\t\tBUBBLE  SORT\n");
	printf("\t\t\t------------\n");
	printf("\nHow many elements?\n");
	scanf("%d",&n);
	a=(int*)malloc(n*sizeof(int));
	printf("\nEnter the elements into the array.\n");
	for(i=0;i<n;++i)
		scanf("%d",&a[i]);
	printf("\nArray before sorting:\n");
	for(i=0;i<n;++i)
		printf("%d\t",a[i]);
	bubble(a,n);
	printf("\n\nArray after sorting:\n");
	for(i=0;i<n;++i)
		printf("%d\t",a[i]);
	getch();
	return 0;
}

void bubble(int a[], int n)
{
	int i,j,temp,swap=1;
	for(i=0;i<n-1&&swap==1;++i)
	{
		swap=0;
		for(j=0;j<n-1-i;++j)
		{
			if(a[j]>a[j+1])
			{
				temp=a[j];
				a[j]=a[j+1];
				a[j+1]=temp;
				swap=1;
			}
		}
	}
}

Related posts:

Leave a Reply

Your email address will not be published. Required fields are marked *