Code For Alls..!

get the code!!

Wednesday, 19 July 2017

Bubble Sort


We take an unsorted array for our example. Bubble sort takes Ο(n2) time so we're keeping it short and precise.
Bubble sort starts with very first two elements, comparing them to check which one is greater.

C code:

#include <stdio.h>
#include <stdlib.h>
void bub(int *a,int n)
{
int i,j,val=0,t;
for(i=0;i<n;i++)
{
val=0;
for(j=0;j<n-i-1;j++)
if(a[j]>a[j+1])
{
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
val=1;
}
if(val==0)
break;
}
}
int cmain(int argc, char *argv[]) {
int *p,i,n;
scanf("%d",&n);
p=malloc(sizeof(int)*n);
for(i=0;i<n;i++)
scanf("%d",p+i);
bub(p,n);
for(i=0;i<n;i++)
printf("%d",*(p+i));
            return 0;
}