#include<stdio.h>
#include<stdlib.h>
int *a;
void m_sort(int,int);
void sort(int,int,int);
main()
{
int n,i;
printf("Enter the number of elements (it should be power of 2) ");
scanf("%d",&n);
a=(int *)calloc(n,sizeof(int));
printf("Enter the values ");
for(i=0;i<n;i++)
scanf("%d",a+i);
m_sort(0,n-1);
printf("The sorted array is \n");
for(i=0;i<n;i++)
printf("%d ",a[i]);
return;
}
void m_sort(int i,int j)
{
int mid;
if(j-i==0)
return;
else
{
mid=(i+j)/2;
m_sort(i,mid);
m_sort(mid+1,j);
sort(i,mid,j);
return;
}
}
void sort(int i,int mid,int j)
{
int *b,k,n,m;
n=i;
m=mid+1;
b=(int *)calloc((j+1),sizeof(int));
for(k=0;k<=j;k++)
{
if(n<=mid&&m<=j)
{
if(a[n]<a[m])
b[k]=a[n++];
else
b[k]=a[m++];
}
else if(n>mid)
b[k]=a[m++];
else
b[k]=a[n++];
}
for(k=0;k<=j;k++)
a[i++]=b[k];
return;
}
Wednesday, 18 September 2013
Tuesday, 17 September 2013
Written by Wyes
#include<stdio.h>
#include<stdlib.h>
int *a;
void quicksort(int,int);
int partition(int,int);
void swap_w(int,int);
int random_partition(int,int);
int random_number(int,int);
main()
{
int i,j,n;
printf("Enter the number of elements ");
scanf("%d",&n);
a=(int *)calloc(n,sizeof(int));
printf("Enter the elements\n");
for(i=0;i<n;i++)
scanf("%d",a+i);
quicksort(0,n-1);
printf("The sorted sequence is\n");
for(i=0;i<n;i++)
printf("%d ",a[i]);
printf("\n");
return;
}
void quicksort(int i,int j)
{
int k;
if(j-i<1)
return;
else
{
k=random_partition(i,j);
quicksort(i,k-1);
quicksort(k+1,j);
return;
}
}
random_partition(int i,int j)
{
int k;
k=random_number(i,j);
swap_w(k,j);
return(partition(i,j));
}
int partition(i,j)
{
int m,n;
m=i-1;
for(n=i;n<j;n++)
{
if(a[n]<=a[j])
{
m++;
swap_w(m,n);
}
}
swap_w(m+1,j);
return(m+1);
}
int random_number(int i,int j)
{
return((rand()%(j-i))+i);
}
void swap_w(int i,int j)
{
int temp;
temp=a[i];
a[i]=a[j];
a[j]=temp;
return;
}
Written by Kousik
/* c program for bubble sort*/
#include<stdio.h>
int a[20];
void bubble(int n)
{
int t, i,j;
for(j=n-1;j>0;j++)
{
for(i=0;i<j;i++)
{
if(a[i+1]>a[i])
{
t=a[i];
a[i]=a[i+1];
a[i+1]=t;
}
}
}
}
int main()
{
int n,i;
printf("Enter the total number of elements: ");
scanf("%d",&n);
printf("Enter the values: ");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
bubble(n);
printf("The sorted sequence: ");
for(i=0;i<n;i++)
printf(" %d",a[i]);
return 0;
}
Subscribe to:
Posts (Atom)