动态数组排序
一个文件,其中数据为abd12068ef
cf3205864lg
egi08832nnnpk
gop66896 hi
pfr52263f
ope48126pk
adc68021p6
vbg32325 4lo
...
文件行数不定,可能有好几万行,要以每行4-8位的整数为关键字进行排序,比如前8行,排序后顺序应为
egi08832nnnpk
abd12068ef
cf3205864lg
vbg32325 4lo
ope48126pk
pfr52263f
gop66896 hi
adc68021p6
我的代码如下:
#include<stdio.h>
#include "string.h"
#include "stdlib.h"
#include <malloc.h>
#define LENGTH 1000000
#define n 100
//void paixu(int shuju[], int shangbiao, int xiabiao);
void paixu(int shuju[], int shangbiao, int xiabiao,char str[][n]);
void main()
{
//获取文件行数
FILE *f;
char c;
//char str[LENGTH][100];
char strr[n];
int lines = 0;//获得的文件行数;
f = fopen("test.txt", "r");
if(f == NULL)
printf("can't open test.txt to read!\n");
while((c = fgetc(f)) != EOF)
if(c == '\n')
lines++;
fclose(f);
if(c != '\n')
lines++;
printf("行数:%d\n",lines);
int m,i,j;
char **str;
int *shuju;
char **b;
str=(char **)malloc(lines*sizeof(char *));
str[0]=(char *)malloc(lines*n*sizeof(char));
b=(char **)malloc(lines*sizeof(char *));
b[0]=(char *)malloc(lines*n*sizeof(char));
shuju= (int *)malloc(sizeof(int)*lines);
FILE *fi;
fi=fopen("test.txt","r");
if(fi==NULL)
{
printf("can't open test.txt to read!\n");
exit(0);
}
for(i=0;i<lines;i++)
{
fgets(strr,100,fi);
strcpy((char*)str[i],strr);
strncpy(b[i],str[i]+3,5);
b[i][5]=0;
shuju[i]=atoi((char*)b[i]);
}
fclose(fi);
free(*str);
free(str);
free(*b);
free(b);
free(shuju);
paixu(shuju,0,lines-1,str);
printf("排序后:\n");
for(i=0;i<lines;i++)
{
printf("%s\n ",str[i]);
}
}
void paixu(int shuju[], int shangbiao, int xiabiao,char str[][n])
{
int i=shangbiao,j=xiabiao;
int shu=i;
int zhongjie;
char bb[100];
if(shangbiao<xiabiao)
{
while(i<j)
{
for(;j>shu;j--)
{
if(shuju[j]<shuju[shu])
{
zhongjie=shuju[j];
shuju[j]=shuju[shu];
shuju[shu]=zhongjie;
strcpy(bb,str[j]);
strcpy(str[j],str[shu]);
strcpy(str[shu],bb);
shu=j;
break;
}
}
i++;
for(;i<shu;i++)
{
if(shuju[i]>shuju[shu])
{
zhongjie=shuju[i];
shuju[i]=shuju[shu];
shuju[shu]=zhongjie;
strcpy(bb,str[i]);
strcpy(str[i],str[shu]);
strcpy(str[shu],bb);
shu=i;
break;
}
}
j--;
}
paixu(shuju,shangbiao,shu-1,str);
paixu(shuju,shu+1,xiabiao,str);
// paixu(shuju,shangbiao,shu-1);
// paixu(shuju,shu+1,xiabiao);
}
}