qsort函数使用

来源:互联网 发布:java等腰三角形代码 编辑:程序博客网 时间:2024/05/29 08:35
qsort函数是stdlib.h中的一个库函数
qsort函数的函数原型为:
 void sqsort(void* base, size_t num, size_t size, int (*compar)(const void*, const void*))

例子1:
#include <stdio.h> /*printf*/
#include <stdlib.h> /*qsort*/
#include <string.h> /*strcmp*/
int compare (const void *a, const void *b)
{
 return ( *(int*)a - *(int*)b );
}
int compare1 (const void *str1, const void *str2)
{
 return strcmp(*(char**)str1,*(char**)str2);
}
int _tmain(int argc, _TCHAR* argv[])
{
 int value[] = {2,1,20,16,95,6}; //整型数组
 char *pStr[] = {"ab","cd","ef","ac"}; //字符串数组
 //整型数组排序
 qsort(value, sizeof(value)/sizeof(int), sizeof(int),compare);
 //字符串数组排序
 qsort(pStr, sizeof(pStr)/sizeof(char*), sizeof(char*), compare1);
 
 for (int i = 0; i < sizeof(value)/sizeof(int); i++)
  printf("%d " ,value[i]);
 printf("\n");
 for (int j = 0; j < sizeof(pStr)/sizeof(char*); j++)
  printf("%s ", pStr[j]);
 return 0;
}
注意:strcpy(char* , const char*)
参考:http://www.cplusplus.com/reference/cstdlib/qsort/?kw=qsort

0 0
原创粉丝点击