学生成绩排序

来源:互联网 发布:被淘宝客服骗了怎么办 编辑:程序博客网 时间:2024/04/26 21:52
/*n.txt文件内存放着学生的信息 信息包括姓名和分数如:张三 90李四 78陈五 82....姓名和分数之间用空格隔开 分数和姓名之间换行要求写一个程序 把这些数据根据分数从小到大进行排序如:李四 78陈五 82张三 90排序结果依然放入这个文件中。大家看下如何写,这里的行数是随机的。我写了一个,因为没有考虑随机的情况,算我写错了 求高手******/#include <stdio.h>#include <stdlib.h>#include <string.h>#defineMAXLEN20 // the max byte infoint getlines();  // return num of the infoint readinfos( char *infoptr[] );  // read the infoint writeinfos( char *infoptr[], int ninfos ); //write //the info that had sortint info_cmp( char *str1, char *str2 );  // compare the score void swap( char *v[], int i, int j );  void qsort_tmp( char *v[], int left, int right );  // sort the infoint main(){int ninfos;  // info num;ninfos = getlines();char *infoptr[ ninfos ]; // the infos pointer arrayif( ninfos == readinfos( infoptr ) ){qsort_tmp( infoptr, 0, ninfos-1 );writeinfos( infoptr, ninfos );return 0;}else{printf( "error: \n" );return 1;}}int getlines(){int nlines = 0;char line[ MAXLEN ];FILE *fp;fp = fopen( "info.txt", "r" );while( fgets( line, MAXLEN, fp ) != NULL )nlines++;close( fp );return nlines;}int readinfos( char *infoptr[] ){int len;int nlines = 0;char *p;char line[ MAXLEN ];FILE *fp;fp = fopen( "info.txt", "r" );while( fgets( line, MAXLEN, fp ) ){len = strlen( line );if( ( p = ( char *)malloc( len ) ) == NULL )return -1;else{strcpy( p, line );infoptr[ nlines++ ] = p;}}fclose( fp );return nlines;}int writeinfos( char *infoptr[], int ninfos ){FILE *fp;int  n = 0;fp = fopen( "info.txt", "w" );while( ninfos-- ){if( fputs( infoptr[n++], fp ) == EOF ){printf( "write infos error\n" );exit(1);}}fclose( fp );return n;}int info_cmp( char *str1, char *str2 ){    int  len1;int  len2;char *str_tmp1;char *str_tmp2;str_tmp1 = str1;str_tmp2 = str2;while( *str_tmp1++ != ' ' );while( *str_tmp2++ != ' ' );len1 = strlen( str_tmp1 );len2 = strlen( str_tmp2 );if( len1 > len2 )return 1;else if( len1 < len2 )return -1;    else{    return  strcmp( str_tmp1, str_tmp2 );}}void swap( char *v[], int i, int j ){char *temp;temp = v[i];v[i] = v[j];v[j] = temp;}void qsort_tmp( char *v[], int left, int right ){int i, last;if( left >= right )return;swap( v, left, ( left+right)/2 );last = left;for( i = left+1; i <= right; i++ )if( info_cmp( v[i], v[left] ) < 0 )swap( v, ++last, i );swap( v, left, last );qsort_tmp( v, left, last-1 );qsort_tmp( v, last+1, right );}

原创粉丝点击