国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C > 正文

C中qsort快速排序使用實例

2020-01-26 15:38:06
字體:
來源:轉載
供稿:網友

簡單的介紹如下。

復制代碼 代碼如下:

/************************************************************************
qsort原型:
void qsort( void *base, size_t num, size_t width,
int (__cdecl *compare )(const void *elem1, const void *elem2 ) );
base:數組首地址
num: 數組元素個數
width: 每個數組元素字節數
compare:比較函數 注意類型轉換
************************************************************************/
#include <stdio.h>
#include <string.h> //strcmp函數
#include <stdlib.h> //qsort函數
#include <math.h> //fabs(double),abs(int)


int intcmp(const void*i1,const void *i2)
{
 return *(int*)i1-*(int*)i2;
}
int doublecmp(const void *d1,const void *d2)
{
 //return *(double*)d1 - *(double*)d2;//出現錯誤 double不精確的
 double tmp=*(double*)d1 - *(double*)d2;
 if(fabs(tmp) < 0.000001)
  return 0;
 else
  return tmp>0 ? 1 : -1;
}
int stringcmp(const void *str1,const void *str2)
{
 return strcmp(*(char**)str1,*(char**)str2);
 /*
 這里為什么是 *(char**)呢?比較函數的參數都是數組元素的地址。
 如果是 int[],那么其元素就是int.傳入的&int[i],那么要比較的話,void *i1轉換
 為 int*的在取值。一樣,對于字符串數組而言,char*s[]其內存放的就是各個串的首地址。
 char*.所以轉換為void *后。其為 &(char*)。所以要從void *轉換回去比較。就要用到二級指針(char**)str1,
 確保str1進過一次尋址后,*str1后為char*.可參見msdn例子。
 */
}

void main()
{
 printf("---------------------C中qsort使用方法(默認遞增)----------------------/n");

 int a[]={1,2,6,8,10,7,9,40,12,6,7};
 printf("-------int[]數組qsort測試-------/nbefore sort:/n");
 for(int i=0;i!=sizeof(a)/sizeof(int);i++)
  printf("%d ",a[i]);
 qsort(a,sizeof(a)/sizeof(int),sizeof(a[0]),intcmp);
 printf("/nafter sort:/n");
 for(int i=0;i!=sizeof(a)/sizeof(int);i++)
  printf("%d ",a[i]);
 printf("/n");


 printf("-------double[]數組qsort測試-------/nbefore sort:/n");
 double d[]={1.12,1.1236,1.36,1.2456,2.48,2.24123,-2.3,0};
 for(int i=0;i!=sizeof(d)/sizeof(double);i++)
  printf("%f ",d[i]);
 qsort(d,sizeof(d)/sizeof(double),sizeof(d[0]),doublecmp);
 printf("/nafter sort:/n");
 for(int i=0;i!=sizeof(d)/sizeof(double);i++)
  printf("%f ",d[i]);
 printf("/n");

 printf("-------string: char*[]數組qsort測試-------/nbefore sort:/n");
 char *str[]={"hello","hi","you","are","baby"};
 for(int i=0;i!=sizeof(str)/sizeof(str[0]);i++)
  printf("%s ",str[i]);
 printf("/nafter sort:/n");
 qsort(str,sizeof(str)/sizeof(str[0]),sizeof(str[0]),stringcmp);
 for(int i=0;i!=sizeof(str)/sizeof(str[0]);i++)
  printf("%s ",str[i]);
 printf("/n");
}

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 鄯善县| 丰宁| 中宁县| 岑溪市| 梁山县| 台安县| 湖南省| 从化市| 上杭县| 宕昌县| 哈巴河县| 得荣县| 怀安县| 南平市| 平陆县| 湘潭市| 穆棱市| 长子县| 前郭尔| 澄江县| 盘山县| 南和县| 澜沧| 湖口县| 博罗县| 天津市| 慈利县| 鄂伦春自治旗| 玛多县| 措美县| 林西县| 临汾市| 承德县| 南华县| 邻水| 淮安市| 南雄市| 循化| 建平县| 团风县| 大名县|