當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C語言 qsort()用法及代碼示例


描述

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 library function - qsort()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。