Built-in functions for sorting arrays in C

Are there any built-in functions in the C programming language for sorting arrays? Or do I need to write my own functions?

+5
source share
6 answers

Check out qsort

Syntax:

#include <stdlib.h>
void qsort( void *buf, size_t num, size_t size, int (*compare)(const void *, const void *) );

Description:

The function qsort()sorts buf (which contains num elements, the size of each size) using Quicksort. The comparison function is used to compare elements in buf. compare should return negative if the first argument is less than the second, zero if they are equal, and positive if the first argument is greater than the second. qsort () sorts buf in ascending order.

+9
source

qsort stdlib.h. , O (nlogn) O (n 2). C99 standard C11 Standard . , , O (nlogn) ( ).

( struct) - .

+7

qsort . , heapsort, mergesort .. , .

, , , .

+6
source

Yes: qsort. This is in stdlib.h.

+3
source

Simple syntax:

int function (const void * a, const void * b) {return ( *(int*)a-(int*)b);}
`qsort(arr_name , sizeofarray , sizeof(int), function);
0
source
 #include <stdio.h> 
 #include <stdlib.h> 

  // This function is used in qsort to decide the relative order 
  // of elements at addresses p and q. 
  int comparator(const void *p, const void *q) 
   { 
      return (*(int*)p-*(int*)q);
      } 

  // A utility function to print an array 
  void printArr(int arr[], int n) 
  { 
     int i; 
     for (i = 0; i < n; ++i) 
     printf("%d ", arr[i]); 
  }  

  // Driver program to test above function 
  int main() 
  { 
     int arr[] = {1, 6, 5, 2, 3, 9, 4, 7, 8, 0}; 
     int size = sizeof(arr) / sizeof(arr[0]); 
     qsort((void*)arr, size, sizeof(arr[0]), comparator); 
     printf("Output array is\n"); 
     printArr(arr, size);  
     return 0; 
   } 
0
source

All Articles