Are there any built in functions in C programming language for sorting arrays? Or do I have to write my own functions?
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.
-
3
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.
-
2
-
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.
-
1I was curious in what standard library exist
mergesort
andheapsort
... turns out they're in FreeBSD's libc. Cool. +1 (Note: they do not appear to exist in glibc.) – Conrad Meyer Jul 17 '12 at 15:26 -
Simple syntax :
int function (const void * a, const void * b) {return ( *(int*)a-(int*)b);}
`qsort(arr_name , sizeofarray , sizeof(int), function);
#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;
}
qsort
instdlib.h
– nhahtdh Jul 17 '12 at 14:35bsearch(3)
is another libc routine in the same vein asqsort(3)
that many people do not know about. (Often, they are used together: you need to sort your array before binary searching it. =)) – Conrad Meyer Jul 17 '12 at 15:24