How To Sort A Vector In C?

Include the standard library header: `#include `

Declare the vector as an array: `int arr[] = {5, 2, 9, 1, 3};`

Get the number of elements: `int n = sizeof(arr) / sizeof(arr[0]);`

Write a comparison function for `qsort`

Use `qsort` to sort the array: `qsort(arr, n, sizeof(int), compare);`

Print or use the sorted array

Example comparison function:

`int compare(const void *a, const void *b) {`

` return (*(int *)a – *(int *)b);`

`}`

Example full code:

`#include `

`#include `

`int compare(const void *a, const void *b) {`

` return (*(int *)a – *(int *)b);`

`}`

`int main() {`

` int arr[] = {5, 2, 9, 1, 3};`

` int n = sizeof(arr) / sizeof(arr[0]);`

` qsort(arr, n, sizeof(int), compare);`

` for (int i = 0; i < n; i++) {`

` printf(“%d “, arr[i]);`

` }`

` return 0;`

`}`

Suggested for You

Trending Today