//对字符串内部按照字符大小进行排序
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
int compare( const void *arg1, const void *arg2 );
int main( int argc, char **argv )
{
char a[255]="18AWSD723adasdf649";
int k=strlen(a);
qsort((void *)a,(size_t)strlen(a),sizeof(char),compare);
printf ("%s",a);
}
int compare( const void *arg1, const void *arg2 )
{
//return -(((char *)arg1)[0]-((char*)arg2)[0]);//降序,这个值取负则为升序
return ((char*)arg1)[0] - ((char*)arg2)[0];
}
//对字符串数组进行排序
#include<stdlib.h>
#include <string.h>
#include <stdio.h>
static int comp(const void * ele1, const void * ele2)
{
return strcmp(*(const char ** ) ele1, *(const char** )ele2);
}
int main()
{
char* str[5]=
{ "sdf",
"fff",
"ttt",
"12aaa",
"erefrerw"
};
int i=0;
qsort(str, 5, sizeof(char*), comp) ;
for(i=0; i<5; i++)
printf("%s/n",str[i]);
return 0;
}
//对整型数组进行排序
#include <stdio.h>
#include <stdlib.h>
int values[] = { 40, 10, 100, 90, 20, 25 };
int compare (const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
int main ()
{
int n;
qsort (values, 6, sizeof(int), compare);
for (n=0; n<6; n++)
printf ("%d ",values[n]);
return 0;
}
qsort的三个例子
最新推荐文章于 2025-04-05 21:06:16 发布
本文介绍如何使用C语言实现不同数据类型的排序,包括字符串、字符串数组及整型数组的排序方法,并提供具体示例代码。
1206





