对二维字符数组排序(2sort和1qsort)

 sort,用到了结构体

第一种sort:

282MS

代码
   
     
#include < stdio.h >
#include
< algorithm >
using namespace std;
struct Array
{
char data[ 30 ];
}dna[
20005 ];
bool operator < (Array const & arr1, Array const & arr2)
{
return strcmp(arr1.data, arr2.data) < 0 ;
}
int main()
{
int n, m, i, count, num[ 20005 ];

while (scanf( " %d%d " , & n, & m) != EOF)
{
if ( ! n && ! m)
return 0 ;
for (i = 0 ; i <= n; i ++ )
num[i]
= 0 ;
for (i = 0 ; i < n; i ++ )
scanf(
" %s " , dna[i].data);
sort(dna, dna
+ n);

count
= 1 ;
for (i = 1 ; i <= n; i ++ )
if (strcmp(dna[i - 1 ].data, dna[i].data) == 0 )
count
++ ;
else
{
num[count]
++ ;
count
= 1 ;
}
for (i = 1 ; i <= n; i ++ )
printf(
" %d\n " , num[i]);
}
return 0 ;
}

第二种sort:

407MS

代码
   
     
#include < stdio.h >
#include
< algorithm >
using namespace std;
struct Array
{
char date[ 30 ];
}dna[
20005 ];
bool cmp(Array arr1, Array arr2)
{
return strcmp(arr1.date, arr2.date) < 0 ;
}
int main()
{
int n, m, i, count, num[ 20005 ];

while (scanf( " %d%d " , & n, & m) != EOF)
{
if ( ! n && ! m)
return 0 ;
for (i = 0 ; i <= n; i ++ )
num[i]
= 0 ;
for (i = 0 ; i < n; i ++ )
scanf(
" %s " , dna[i].date);
sort(dna, dna
+ n, cmp);

count
= 1 ;
for (i = 1 ; i <= n; i ++ )
if (strcmp(dna[i - 1 ].date, dna[i].date) == 0 )
count
++ ;
else
{
num[count]
++ ;
count
= 1 ;
}
for (i = 1 ; i <= n; i ++ )
printf(
" %d\n " , num[i]);
}
return 0 ;
}

qsort:

329MS

代码
   
     
#include < stdio.h >
#include
< stdlib.h >
#include
< string .h >
int cmp( const void * a, const void * b)
{
return (strcmp(( char * )a,( char * )b));
}
int main()
{
int n, m, i, count, num[ 20005 ];
char dna[ 20005 ][ 30 ];
while (scanf( " %d%d " , & n, & m) != EOF)
{
if ( ! n && ! m)
return 0 ;
for (i = 0 ; i <= n; i ++ )
num[i]
= 0 ;
for (i = 0 ; i < n; i ++ )
scanf(
" %s " , dna[i]);
qsort(dna, n,
sizeof (dna[ 0 ]), cmp);

count
= 1 ;
for (i = 1 ; i <= n; i ++ )
if (strcmp(dna[i - 1 ], dna[i]) == 0 )
count
++ ;
else
{
num[count]
++ ;
count
= 1 ;
}
for (i = 1 ; i <= n; i ++ )
printf(
" %d\n " , num[i]);
}
return 0 ;
}

你可能感兴趣的:(sort)