1. Bubble Sort Example (Array of Int)
void main()
{
int a[5],i,j,t;
clrscr();
printf("Enter array : ");
for(i=0;i<=4;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<=3;i++)
{
for(j=0;j<=3-i;j++)
{
if(a[j] > a[j+1])
{
t = a[j];
a[j] = a[j+1];
a[j+1] = t;
}
}
}
printf("\noutput\n");
for(i=0;i<=4;i++)
{
printf("%d\t",a[i]);
}
getch();
}
2. Bubble Sort Example (Roll Number-wise -> Array of student)
struct student
{
int rn;
char name[34];
};
void main()
{
struct student a[5],t;
int i,j;
clrscr();
printf("Enter data : ");
for(i=0;i<=4;i++)
{
scanf("%d%s",&a[i].rn,&a[i].name);
}
for(i=0;i<=3;i++)
{
for(j=0;j<=3-i;j++)
{
if(a[j].rn > a[j+1].rn)
{
t = a[j];
a[j] = a[j+1];
a[j+1] = t;
}
}
}
printf("\noutput\n");
for(i=0;i<=4;i++)
{
printf("%d\t%s\n",a[i].rn,a[i].name);
}
getch();
}
3. Bubble Sort Example (Name-wsie -> Array of student)
struct student
{
int rn;
char name[34];
};
void main()
{
struct student a[5],t;
int i,j,n;
clrscr();
printf("Enter data : ");
for(i=0;i<=4;i++)
{
scanf("%d%s",&a[i].rn,&a[i].name);
}
for(i=0;i<=3;i++)
{
for(j=0;j<=3-i;j++)
{
n = strcmp(a[j].name,a[j+1].name);
if(n>0)
{
t = a[j];
a[j] = a[j+1];
a[j+1] = t;
}
}
}
printf("\noutput\n");
for(i=0;i<=4;i++)
{
printf("%d\t%s\n",a[i].rn,a[i].name);
}
getch();
}
4. Merge Sort Example
/*
Merge Sort : both the array must be in same sorted order
cs : 98 95 80 70 69
IT : 99 88 87 86 50 40 33 32
a : 99 98 95 88 87 86 80 70 69 50 40 33 32
*/
void main()
{
int a[5],b[4],c[9];
int i,j,k;
clrscr();
printf("Enter first array \n");
for(i=0;i<=4;i++)
{
scanf("%d",&a[i]);
}
printf("Enter second array \n");
for(i=0;i<=3;i++)
{
scanf("%d",&b[i]);
}
//merge sort logic
i = j = k = 0;
while(i<=4 && j<=3)
{
if(a[i] < b[j])//for descending just replace < sign with > sign
{
c[k] = a[i];
i++;
}
else
{
c[k] = b[j];
j++;
}
k++;
}
while(i<=4)
{
c[k] = a[i];
i++;
k++;
}
while(j<=3)
{
c[k] = b[j];
j++;
k++;
}
printf("\nOutput\n\n");
for(i=0;i<=8;i++)
{
printf("%d\n",c[i]);
}
getch();
}
5. Quick Sort Example
/*
Quick sort
key p=1 q=9
0 : 80 90 70 50 40 32 140 54 650 45 <== A
key p=1 p=2 p=3 p=4 p=5 p=6 q=7 q=8 q=9
1 : 80 45 70 50 40 32 140 54 650 90 <== A
key q,p=6 p,q=7
2 : 80 45 70 50 40 32 54 140 650 90 <== A
q=6
3 : 54 45 70 50 40 32 80 140 650 90 <== A
*/
void sort(int a[],int low,int high);
int split(int a[],int low,int high);
void main()
{
int a[10];
int low=0,high=9,i;
clrscr();
printf("Enter array\n");
for(i=0;i<=9;i++)
{
scanf("%d",&a[i]);
}
sort(a,low,high);
printf("After sortng\n\n");
for(i=low;i<=high;i++)
{
printf("%d\t",a[i]);
}
getch();
}
void sort(int a[],int low,int high)
{
int n;
if(low a[p])//80 > 140
{
p++;
}
while(key < a[q]) //80 < 54
{
q--;
}
if(p