qsort() in Cqsort() is a pre-defined standard function in the C library. We can use this function to sort an array in ascending or descending order. It internally uses the quick sort algorithm, hence the name qsort. It can sort an array of any data type, including strings and structures. It works well and is efficient to implement. There is a function sort() in C++ similar to qsort() in C. In aspects like running time, safety, and flexibility, sort() outdoes qsort(). This tutorial explains the function qsort() with examples. C standard did not specify the complexity of the function, but as internally it follows the quick sort algorithm, its average time complexity is tentatively taken to be O(n*logn). The function is defined in the stdlib header file; hence we need to include it before using it. Syntax of the function:array: The array to be sorted. number: Number of elements in the array that we want to sort size: Size of an individual element of the array function: Custom comparison function we need to write in a specified format: Specified format of the function:
Now, we will explore the functions for sorting arrays of different data types.1. Sorting Integers:Output: Enter the size of the array to be sorted: 5 Enter elements into the array: 98 34 89 0 2 The sorted array: [0, 2, 34, 89, 98] Understanding:In these two lines: int a = *(int*) num1; int b = *(int*) num2; The input array is of type <int>. Hence, we must typecast the void pointers into integer pointers before performing any operations to allocate the required memory. We stored the values the two pointers are pointing at in two other integer variables, a and b. Then, we compared both values using the comparison operators. Instead of using two more temporary variables, we can write a one-line code:
2. Sorting stringsOutput: Enter the size of the array to be sorted: 5 Enter elements into the array: hi hello how are you The sorted array: [are, hello, hi, how, you] Understanding:
3. Sorting an Array of StructureOutput: Original array: [[1, 7], [4, 0], [9, 4], [8, 8], [2, 4]] Sorted array: [[1, 7], [2, 4], [4, 0], [8, 8], [9, 4]] Understanding:We declared an array of type Structure, meaning every element in the array is an array of structure elements. In the above program, the structure has two integer elements. The task is to sort the array with respect to the first Structure element, and if any two first elements are equal, we need to sort it using the second element. Example: [[1, 2], [3, 4], [1, 4]] Sorted array: [[1, 2], [1, 4], [3, 4]] We used the rand() function to generate random elements in the array. In the compare() function, we need to typecast the two pointers to type structure. The specialty of using qsort() is the custom compare function that we can design the way we want. We can also sort a few elements in an array and leave the rest unsorted. Next TopicQuiz game in C |