描述
C庫函數void qsort(void *base, size_t nitems, size_t size, int (*compar)(const void *, const void*))對數組進行排序。
聲明
以下是 qsort() 函數的聲明。
void qsort(void *base, size_t nitems, size_t size, int (*compar)(const void *, const void*))
參數
base- 這是指向要排序的數組的第一個元素的指針。
nitems- 這是 base 指向的數組中的元素數。
size- 這是數組中每個元素的字節大小。
compar- 這是比較兩個元素的函數。
返回值
此函數不返回任何值。
示例
下麵的例子展示了 qsort() 函數的用法。
#include <stdio.h>
#include <stdlib.h>
int values[] = { 88, 56, 100, 2, 25 };
int cmpfunc (const void * a, const void * b) {
return ( *(int*)a - *(int*)b );
}
int main () {
int n;
printf("Before sorting the list is:\n");
for( n = 0 ; n < 5; n++ ) {
printf("%d ", values[n]);
}
qsort(values, 5, sizeof(int), cmpfunc);
printf("\nAfter sorting the list is:\n");
for( n = 0 ; n < 5; n++ ) {
printf("%d ", values[n]);
}
return(0);
}
讓我們編譯並運行上麵的程序,將產生以下結果 -
Before sorting the list is: 88 56 100 2 25 After sorting the list is: 2 25 56 88 100
相關用法
- C語言 宏 assert()用法及代碼示例
- C語言 vprintf()用法及代碼示例
- C語言 宏 va_start()用法及代碼示例
- C語言 setlocale()用法及代碼示例
- C語言 fread()用法及代碼示例
- C語言 sinh()用法及代碼示例
- C語言 宏 offsetof()用法及代碼示例
- C語言 feof()用法及代碼示例
- C語言 scanf()用法及代碼示例
- C語言 imagesize()用法及代碼示例
- C語言 getarcoords()用法及代碼示例
- C語言 isdigit()用法及代碼示例
- C語言 clock()用法及代碼示例
- C語言 strcspn()用法及代碼示例
- C語言 setlinestyle()用法及代碼示例
- C語言 fmod()用法及代碼示例
- C語言 showbits()用法及代碼示例
- C語言 div()用法及代碼示例
- C語言 outtextxy()用法及代碼示例
- C語言 sqrt()用法及代碼示例
注:本文由純淨天空篩選整理自 C library function - qsort()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。