好程序员训练营
<A href="http://www.goodprogrammer.org/" target="blank">ios培训</A>
------我的c语言笔记,期待与您交流!
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAXLEN 1000
#define MAXLINES 5000
#define ALLOCSIZE 10000
static char allocbuf[ALLOCSIZE];
static char *allocp=allocbuf;
int numcmp(char *,char *);
int getline(char s[],int lim);
/*getline函数:将行保存到s中,并返回该行的长度;输入参数,指向一行的指针和最大行长度*/
char *alloc(int n);
/* alloc函数:返回指向n个字符的指针;输入:字符的数量*/
int strcmp(char *,char *);
char *lineptr[MAXLINES];
int readlines(char *lineptr[],int nlines);
void writelines(char *lineptr[],int nlines);
void qsort(void *lineptr[],int left,int right,int(*comp)(void *,void *));
int numcmp(char *,char *);
int strcmp(char *,char *);
/* alloc函数:返回指向n个字符的指针*/
char *alloc(int n)
{
if(allocbuf+ALLOCSIZE-allocp>=n)
{
allocp+=n;
return allocp-n;
}
else
return 0;
}
/* afree函数:释放p指向的存储区*/
void afree(char *p)
{
if(p>=allocbuf && p<allocbuf+ALLOCSIZE)
allocp=p;
}
/*getline函数:将行保存到s中,并返回该行的长度*/
int getline(char s[],int lim)
{
int c,i;
i=0;
while(--lim>0 &&(c=getchar())!=EOF && c!='\n')
s[i++]=c;
if(c=='\n')
s[i++]=c;
s[i]='\0';
return i;
}
/*numcmp函数:按数值顺序比较字符串s1和s2*/
int numcmp(char *s1,char *s2)
{
double v1,v2;
v1=atof(s1);
v2=atof(s2);
if(v1<v2)
return -1;
else if(v1>v2)
return 1;
else
return 0;
}
/*qsort函数:以递增顺序对v[left]...v[right]进行排序*/
void swap(void *v[],int i,int j)
{
void *temp;
temp=v[i];
v[i]=v[j];
v[j]=temp;
}
void qsort(void *v[],int left,int right ,int (*comp)(void *,void *))
{
int i,last;
void swap(void *v[],int,int);
if (left>=right)
return;
swap(v,left,(left+right)/2);
last=left;
for(i=left+1;i<=right;i++)
if( (*comp) (v[i],v[left])<0)
swap(v,++last,i);
swap(v,left,last);
qsort(v,left,last-1,comp);
qsort(v,last+1,right,comp);
}
/* readlines函数:读取输入行;输入参数:指针数组和最大行数;返回:返回行数*/
int readlines(char *lineptr[],int maxlines)
{
int len,nlines;
char *p,line[MAXLEN];
nlines=0;
while((len=getline(line,MAXLEN))>0)
if(nlines>=maxlines||(p=alloc(len))==NULL)
return -1;
else
{
line[len-1]='\0';
strcpy(p,line);
lineptr[nlines++]=p;
}
return nlines;
}
/*strcmp函数:根据s按照字典顺序小于、等于或大于t的结果分别返回负整数、0或正整数 */
int strcmp(char *s,char *t)
{
int i;
for(i=0;s[i]==t[i];i++)
if(s[i]=='\0')
return 0;
return s[i]-t[i];
}
void writelines(char *lineptr[],int nlines)
{
while(nlines-->0)
printf("%s\n",*lineptr++);
}
/*对输入的文本行进行排序*/
int main()
{
int nlines;
int numeric=0;
int argc=3;
char *argv[]={"echo","-n,","world",0};
if(argc>1 && strcmp(argv[1],"-n")==0)
numeric=1;
if((nlines=readlines(lineptr,MAXLINES))>=0)
{
qsort((void **)lineptr,0,nlines-1,(int(*)(void *, void*))(numeric? numcmp : strcmp ));
writelines(lineptr,nlines);
return 0;
}
else
{
printf("input too big to sort\n");
return 1;
}
}