#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef int (*__compar_fn_t )(const void*,const void*) ;
int cmp_i( int *a , int *b )
{
return (*a-*b) ;
}
int cmp_c( char *a, char *b )
{
return (*a-*b);
}
#define ZERO 0.001
int cmp_f( float *a , float *b ) {
return (*a-*b>ZERO?1:(*a-*b<ZERO?-1:0));
}
int cmp_s( char **a , char **b ) {
char *s , *d ;
s = *a ;
d = *b ;
if ( NULL == s || NULL == d ) {
return -1 ;
}
for ( ; *s == *d ; s++ ,d++) ;
return ( *s - *d);
}
void test_qsort() {
int n , i ;
int a[] = { 1 , 3 , 2 , 4 , 5 , 7 , 6 };
char b[] = {'b' , 'c' , 'a' , 'd' , 'e' };
float c[] = { 1.1 , 2.1 , 3.5 , 5.6 , 6.5};
char *d[] = {"foo","bar","hello","world","ilove","iloveyou"} ;
n = sizeof(a)/sizeof(int);
qsort(a,n,sizeof(int),(__compar_fn_t)cmp_i);
for ( i = 0 ; i < n ; i++ ) {
printf("%-4d",a[i]);
}
printf("\n");
n = sizeof(b)/sizeof(char) ;
qsort(b,n,sizeof(char),(__compar_fn_t)cmp_c);
for ( i = 0 ; i < n ; i++ ) {
printf("%-3c",b[i] );
}
printf("\n");
n = sizeof(c)/sizeof(float);
qsort(c,n,sizeof(float),(__compar_fn_t)cmp_f);
for ( i = 0 ; i < n ; i++ ) {
printf("%-12f",c[i] );
}
printf("\n");
n = sizeof(d)/sizeof(char*);
qsort(d,n,sizeof(char*),(__compar_fn_t)cmp_s);
for ( i = 0 ; i < n ; i++ ) {
printf("%-12s",d[i] );
}
printf("\n");
}
int main( int argc , char *argv[] ) {
int i , n , m , max,sel , j ;
if ( argc < 2 ) {
exit(0);
}
//test_qsort();
char *a , *b[56] , *c;
//这里用来求重复子串 利用后缀数组
a = argv[1] ;
n = strlen( a );
for ( i = 0 ; i < n ; i++ )
//求出后缀数组
{
b[i] = a+i ;
}
m = i -1 ;
qsort(b,m,sizeof(char*),(__compar_fn_t)cmp_s);
//按字符串排序
for ( i = 0 ; i < m ; i++ ) {
printf("%-12s\n",b[i]);
}
max = 0 ;
sel = 0 ;
for ( i = 0 ; i < m ; i++ )
//一遍循环求最大值
{
for (j=0 ; b[i][j] == b[i+1][j]; j++ );
if ( j + 1 > max ) {
sel = i ;
max = j ;
}
}
c = "origin string" ;
printf("%-24s:%s\n",c,a);
c = "max common substring";
printf("%-24s:",c);
for ( i = 0 ; i < max ; i++ ) {
printf("%c",b[sel][i]);
}
printf("\n");
return 0;
}
qsort回调函数
最新推荐文章于 2024-06-16 09:00:00 发布