What is qsort in C.

With the function qsort represents stdlib.c an extremely fast sorting function is available that can sort any array. Likewise is bsearch out stdlib.c a very high-performance search function that can search arrays of any type for an element, provided the array is sorted. A function pointer to a comparison function must be transferred to both functions.


void qsort (void * arrBase, size_t arrSize, size_t elemSize, int (* compare) (const void *, const void *))

First we sort an array of 10 int numbers. We use malloc to get memory that contains random values. We sort these.

First of all, the comparison function for the ascending order.

int compareInt (const void * i1, const void * i2) {return (* (int *) i1 - * (int *) i2); }

The example

void qsortDemo () {puts ("qsortdemo"); #define MAX 10 int * iArr = (int *) malloc (MAX * sizeof (int)); if (iArr == NULL) return; printf ("unsorted:"); for (int i = 0; i One possible issue

qsortdemo unsorted: 4083008 4063608 1835102823 1701603654 977485171 1869762652 1835102823 1197237613 1768254821 1835103086 sorted: 4063608 4083008 977485171 1197237613 170160365104 1768254821 1835102823 186210651086

void * bsearch (const void * toSearch, const void * arrBase, size_t arrSize, size_t elemSize, int (* compare) (const void *, const void *))

Around bsearch need to apply will sort first. We generate forty two-digit numbers between 10 and 99 with the random generator and sort them. Then we look for the number 42. We take that of the previous example as a comparison function.

void bsearchDemo () {puts ("bsearchdemo"); #define ARRSIZE 40 int iArr [ARRSIZE]; // initialize the random number generator with the help of the current date srand (time (NULL)); // generate and output random numbers printf ("unsorted:"); for (int i = 0; i Here are two issues

bsearchdemo unsorted: 79 50 23 47 48 84 21 68 64 44 25 92 19 97 12 44 69 43 24 70 45 37 35 75 28 37 11 52 76 53 43 87 53 56 28 24 71 44 96 33 sorted: 11 12 19 21 23 24 24 25 28 28 33 35 37 37 43 43 44 44 44 45 47 48 50 52 53 53 56 64 68 69 70 71 75 76 79 84 87 92 96 97 number 42 not found bsearchdemo unsorted: 10 98 31 79 24 91 62 15 82 38 36 60 74 36 72 75 46 39 62 59 86 31 29 97 59 99 96 19 97 67 81 91 16 38 59 92 20 63 42 62 assorted: 10 15 16 19 20 24 29 31 31 36 36 38 38 39 42 46 59 59 59 60 62 62 62 63 67 72 74 75 79 81 82 86 91 91 92 96 97 97 98 99 number 42 found index is 14