首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

c语言大规模排序解决方案

2012-08-16 
c语言大规模排序//#include stdafx.h#include stdio.h#include string.h#define N 4void main(){cha

c语言大规模排序

//#include "stdafx.h"
#include "stdio.h"
#include "string.h"
#define N 4
void main()
{

char a[N][10] = {"wsdju","Wklchina","women","wlala"};
int index[N];
int i,j,temp;
for(i=0;i<N;i++)
index[i] = i;  
/*排序*/
for(i=0;i<N;i++){
for (j=0;j<N-i-1;j++){
if(strcmp(a[index[j]],a[index[j+1]])>0){
temp = index[j];
index[j] = index[j+1];
index[j+1] = temp;
}
}
}

/*输出结果*/
for(i=0;i<N;i++)
printf("%s\n",a[index[i]]);

}

以上是对4个单词进行排序,现在我要对4000多个单词进行排序,这4000多个单词从一个txt文本文档里读取,具体数目未定,但数量级在千以上,请问有没有好的实现办法?

[解决办法]

C/C++ code
[User:root Time:09:46:36 Path:/home/liangdong/c]$ ./output 12str_table[0]:1str_table[1]:2[User:root Time:09:46:38 Path:/home/liangdong/c]$ cat src/main.c #include <stdio.h>#include <stdlib.h>#include <string.h>int main(int argc, char* const argv[]) {        char line[100];        char* *str_table = NULL;        int size = 0;        int i = 0;        for ( ; i != 2; ++ i) {                scanf("%s", line);                str_table = realloc(str_table, (++ size) * sizeof(char*));                str_table[size - 1] = strdup(line);        }        for (i = 0 ; i != 2; ++ i) {                printf("str_table[%d]:%s\n", i, str_table[i]);                free(str_table[i]);        }        free(str_table);        return 0;}
[解决办法]
这才是真正的大规模吧:
C/C++ code
//将out.txt文件中的内容排序并去重,结果保存到unique.txt中#include <stdio.h>#include <stdlib.h>#define MAXLNO 10000000 //能处理的最大行数#define MAXLEN 20       //能处理的最大行宽,包括行尾的\n和字符串尾的\0char buf[MAXLNO][MAXLEN];int ln,i;FILE *f;int cmpfun( const void *arg1, const void *arg2 ) {    return strcmp((const char *)arg1,(const char *)arg2);}int main() {    f=fopen("out.txt","r");    if (NULL==f) {        printf("Can not find file out.txt\n");        return 1;    }    ln=0;    while (1) {        if (NULL==fgets(buf[ln],MAXLEN,f)) break;        ln++;        if (ln>=MAXLNO) {            printf("Lines >%d ignored.",MAXLNO);            break;        }    }    fclose(f);    if (ln>1) qsort(buf,ln,MAXLEN,cmpfun);    f=fopen("unique.txt","w");    if (NULL==f) {        printf("Can not create file unique.txt\n");        return 2;    }    fprintf(f,"%s",buf[0]);    if (ln>1) for (i=1;i<ln;i++) {        if (strcmp((const char *)buf[i-1],(const char *)buf[i])) fprintf(f,"%s",buf[i]);    }    fclose(f);    return 0;} 

热点排行