Tuesday, 3 January 2012

Buuble Sort of an array

/* Without using function  */


#include<stdio.h>
#include<conio.h>
void main()
{
int i=0,n,temp,j;
int arr[20];
clrscr();
printf("How many elements you want in the array: ");
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
for(i=0;i<n;i++)
{
for(j=0;j<n-1;j++)
{


if(arr[j]>arr[j+1])
{
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
printf("The sorted array is:  \n");
for(i=0;i<n;i++)
printf("  %d  ",arr[i]);
getch();
}


/* Bubble sort using function */



#include<stdio.h>

#include<conio.h>
void bubble_sort(int a[],int n);
void main()
{
int a[100],n,i;
clrscr();
printf("How many element in the array: ");
scanf("%d",&n);
printf("Enter the elements of array: ");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
bubble_sort(a,n);
printf("Elements of array after sorting: ");
for(i=0;i<n;i++)
printf("  %d  ",a[i]);
getch();
}
void bubble_sort(int a[],int n)
{
int temp,i,j;
for(i=0;i<n;i++)
{
for(j=0;j<n-1;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
}