Quick Sort
#include<stdio.h>
#include<conio.h>
void swap(int *a,int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
int par(int *a,int p,int r)
{
int i=p-1,j=p,pivot;
pivot=r;
while(j<pivot)
{
if(a[j]<=a[pivot])
{
swap(&a[j],&a[i+1]);
i++;
j++;
}
else
{
j++;
}
}
swap(&a[i+1],&a[pivot]);
return i+1;
}
void quicksort(int *a,int p,int r)
{
int q;
if(p<r)
{
q=par(a,p,r);
quicksort(a,p,q-1);
quicksort(a,q+1,r);
}
}
main()
{
FILE *f=fopen("hinput.txt","r");
char c[10];
int a[10],i=0;
while(fscanf(f,"%s",c)!=EOF)
{
a[i++]=atoi(c);
}
int n=i-1;
for(i-=1;i>=0;i--)
printf("a[%d]=%d\n",n-i,a[n-i]);
quicksort(a,0,n);
printf("\n#######\n Quick Sort\n#########\n");
for(i=0;i<=n;i++)
printf("a[%d]=%d\n",i,a[i]);
fclose(f);
getch();
}
#include<stdio.h>
#include<conio.h>
void swap(int *a,int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
int par(int *a,int p,int r)
{
int i=p-1,j=p,pivot;
pivot=r;
while(j<pivot)
{
if(a[j]<=a[pivot])
{
swap(&a[j],&a[i+1]);
i++;
j++;
}
else
{
j++;
}
}
swap(&a[i+1],&a[pivot]);
return i+1;
}
void quicksort(int *a,int p,int r)
{
int q;
if(p<r)
{
q=par(a,p,r);
quicksort(a,p,q-1);
quicksort(a,q+1,r);
}
}
main()
{
FILE *f=fopen("hinput.txt","r");
char c[10];
int a[10],i=0;
while(fscanf(f,"%s",c)!=EOF)
{
a[i++]=atoi(c);
}
int n=i-1;
for(i-=1;i>=0;i--)
printf("a[%d]=%d\n",n-i,a[n-i]);
quicksort(a,0,n);
printf("\n#######\n Quick Sort\n#########\n");
for(i=0;i<=n;i++)
printf("a[%d]=%d\n",i,a[i]);
fclose(f);
getch();
}
No comments:
Post a Comment
Have some problem with this code? or Request the code you want if you cant find it in Blog Archive.