Here is a Quick Sort program in C, the program compiles without any errors. But When run and choose random numbers to sort. I get output as follows,
sam@TechTosh ~ $ gcc quick.c
sam@TechTosh ~ $ ./a.out
1> Read from file
2> Random no. Generator
Enter the Choice
2
Starting 10
Segmentation fault
And here is the program, I have debugged a lot of errors from this program, at last its running but cant nor it sort neither it takes input from both types of input that is Read from file or random number generation.
#include<stdio.h>
#include<time.h>
#include<values.h>
#include<malloc.h>
#include<stdlib.h>
#include<unistd.h>
int *a;
void swap(int i,int j)
{
int temp;
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
int partition(int l,int r)
{
int p,i,j;
p=a[l];
i=l;
j=r+1;
while(i<j)
{
for(i=i+1;i<r&&a[i]<p;i++)
for(j=j-1;j>l&&a[i]>p;j++)
swap(i,j);
}
swap(i,j);
swap(l,j);
return j;
}
void quick(int l,int r)
{
int s,i;
if(l<r)
{
s=partition(l,r);
//delay(1);
quick(l,s-1);
quick(s+1,r);
}
}
void main()
{
FILE *fp,*fp1;
clock_t c1,c2;
int n,i,j,l,r,datasize=1,ch,x,c;
long int m;
char file[10];
do
{
printf("\n1> Read from file\n2> Random no. Generator\n\n");
printf("\nEnter the Choice\n");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("\nEnter n value\n");
scanf("%d",&n);
a=(int*)calloc(n,sizeof(int));
printf("Enter the filename\n");
scanf("%s",file);
fp1=fopen(file,"r");
i=0;
while(!feof(fp1))
{
fscanf(fp1,"%d",&a[i]);
i++;
}
fclose(fp1);
for(i=0;i<n;i++)
printf("%d\t",a[i]);
quick(0,n-1);
printf("\nSorted Elements are\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
free(a);
break;
case 2: m=100;
fp=fopen("new.dat","w");
while(datasize<=10)
{
printf("Starting %ld\n",m);
a=(int*)calloc(m,sizeof(int));
for(i=0;i<=m-1;i++)
{
a[i]=rand()%MAXINT;
printf("%d",a[i]);
}
c1=clock();
quick(0,m-1);
c2=clock();
free(a);
fprintf(fp,"%ld\t %ld\n",m,(c2-c1)/CLOCKS_PER_SEC);
datasize++;
m=m+100;
}
fclose(fp);
break;
default: break;
}
printf("To continue, Press 1 else other for Exit!");
scanf("%d",&c);
}
while(c==1);
}