qsort is a quick sort function provided by the C standard library, located in the stdlib.h header file. It can sort arrays of any type.The prototype of the qsort function is as follows:void qsort(void *base, size_t nitems, size_t size, int (*compar)(const void *, const void *));
| Parameter | Function | Example |
|---|---|---|
<span>base</span> |
Base address of the array | <span>arr</span> |
<span>nitems</span> |
Total number of elements | <span>len</span> |
<span>size</span> |
Size of a single element in bytes | <span>sizeof(unsigned int)</span> |
<span>compar</span> |
The soul function of the sorting rule | See detailed explanation below |
The comparison function is defined as follows:int compar(const void *a, const void *b);– This function must return an integer value:– If `a` should be placed before `b`, return a **negative number**.– If `a` and `b` are equal, return **0**.– If `a` should be placed after `b`, return a **positive number**.
int compare(const void *a, const void *b) { // Key operation for ascending order: return *(unsigned int*)a - *(unsigned int*)b; // For descending order, simply swap a and b: // return *(unsigned int*)b - *(unsigned int*)a;}
Example code is as follows:
#include <stdio.h>#include <stdlib.h>// Quick sort comparison functionint compare(const void *a, const void *b) { return (*(unsigned int*)a - *(unsigned int*)b);}float average_value(unsigned int *arr, unsigned int len, unsigned int n) { // 1️⃣ Parameter validity check if (len == 0 || n * 2 >= len) return 0.0f; // 2️⃣ Quick sort (ascending order) qsort(arr, len, sizeof(unsigned int), compare); // 3️⃣ Calculate the sum of the middle segment (skip the first and last n values) float total = 0; for (unsigned int i = n; i < len - n; i++) { total += arr[i]; } // 4️⃣ Calculate the truncated mean return total / (len - 2 * n);}// Test input data: {1,2,3,4,5,6,7,8,9,10} Excluded values: n=1int main() { // Test data: integers from 1 to 10 unsigned int data[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; unsigned int len = sizeof(data) / sizeof(data[0]); // Call function (n=1: exclude 1 highest and 1 lowest score) printf("Truncated mean: %.2f\n", average_value(data, len, 1)); // Output: Truncated mean: 5.50 // Call function (n=2: exclude 2 highest and 2 lowest scores) printf("Truncated mean: %.2f\n", average_value(data, len, 2)); // Output: Truncated mean: 5.50 }
🚀 Key Points of the Code:
-
Quick Sort:
<span>qsort()</span>function sorts the original data in ascending order -
Outlier Removal: Parameter
<span>n</span>controls the amount of data to be excluded from both ends (e.g.,<span>n=1</span>excludes one highest and one lowest value) -
Error Prevention Mechanism: Checks if the
<span>n</span>value exceeds the valid range -
Dynamic Calculation: The denominator for the mean is automatically adjusted to
<span>len - 2*n</span>
Writing code is not easy; if you find it useful, please give a 【follow】 and 【recommend】. Your likes are my motivation to keep writing, thank you!