欧美大屁股bbbbxxxx,狼人大香伊蕉国产www亚洲,男ji大巴进入女人的视频小说,男人把ji大巴放进女人免费视频,免费情侣作爱视频

歡迎來到入門教程網(wǎng)!

C語言

當前位置:主頁 > 軟件編程 > C語言 >

C中qsort快速排序使用實例

來源:本站原創(chuàng)|時間:2020-01-10|欄目:C語言|點擊: 次

簡單的介紹如下。

復制代碼 代碼如下:

/************************************************************************
qsort原型:
void qsort( void *base, size_t num, size_t width,
int (__cdecl *compare )(const void *elem1, const void *elem2 ) );
base:數(shù)組首地址
num: 數(shù)組元素個數(shù)
width: 每個數(shù)組元素字節(jié)數(shù)
compare:比較函數(shù) 注意類型轉(zhuǎn)換
************************************************************************/
#include <stdio.h>
#include <string.h> //strcmp函數(shù)
#include <stdlib.h> //qsort函數(shù)
#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;//出現(xiàn)錯誤 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**)呢?比較函數(shù)的參數(shù)都是數(shù)組元素的地址。
 如果是 int[],那么其元素就是int.傳入的&int[i],那么要比較的話,void *i1轉(zhuǎn)換
 為 int*的在取值。一樣,對于字符串數(shù)組而言,char*s[]其內(nèi)存放的就是各個串的首地址。
 char*.所以轉(zhuǎn)換為void *后。其為 &(char*)。所以要從void *轉(zhuǎn)換回去比較。就要用到二級指針(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[]數(shù)組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[]數(shù)組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*[]數(shù)組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");
}

上一篇:二叉樹先根(先序)遍歷的改進

欄    目:C語言

下一篇:堆排序算法(選擇排序改進)

本文標題:C中qsort快速排序使用實例

本文地址:http://mengdiqiu.com.cn/a1/Cyuyan/3822.html

網(wǎng)頁制作CMS教程網(wǎng)絡編程軟件編程腳本語言數(shù)據(jù)庫服務器

如果侵犯了您的權(quán)利,請與我們聯(lián)系,我們將在24小時內(nèi)進行處理、任何非本站因素導致的法律后果,本站均不負任何責任。

聯(lián)系QQ:835971066 | 郵箱:835971066#qq.com(#換成@)

Copyright © 2002-2020 腳本教程網(wǎng) 版權(quán)所有