Built in functions for sorting arrays in C

27,509

Solution 1

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 qsort() function sorts buf (which contains num items, each of size size) using Quicksort. The compare function is used to compare the items 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.

Solution 2

You can use qsort in stdlib.h. It is quick-sort algorithm, which has average time complexity of O(nlogn) and worst case complexity of O(n2). The C99 standard and even the newer C11 Standard doesn't mandate the implementation or time complexity of the function. However, it is very likely that common implementation will use algorithm that yields average case O(nlogn) time complexity (which is optimal for sorting by comparison).

You can use this to sort any kind of array (even struct) - but you must provide a comparison function to compare between 2 elements of the array.

Solution 3

qsort is well known. There are others also like heapsort, mergesort etc. Please check the link for more details.

Please note that all of them take comparison functions as input, making them easily usable with native as well as user created data types.

Solution 4

Yes: qsort. It's in stdlib.h.

Solution 5

 #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; 
   } 
Share:
27,509
CluelessNoob
Author by

CluelessNoob

Updated on October 14, 2020

Comments

  • CluelessNoob
    CluelessNoob over 3 years

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