# Qsort

• 10-28-2001
Tombear
Qsort
There is a question here.

Write a function which, given an array of structures specified by:

struct item
{
int ref_num,minutes,cost_per_min;
float total_weight;
};

recorders the array(in place) using the qsort() function in stdlib.h so that the array elements have the 'sort_field'(th) field arrange in ascending order after the sort(sort_field has valid values 1 to 4). The 'num_items' parameter indicates the number of array elements to be sorted. The prototype is:

void recorder( struct item item_array[], int num_items, int sort_field);

How to use sandard qsort() function?
I think insertion sort could be easied to be used it for this quesiton?
Pls tell me how to use qsort to do it?
Thanks a lot.
• 10-28-2001
Salem
> There is a question here.
There certainly is

> How to use sandard qsort() function?
Like so
Code:

```#include <stdio.h> #include <stdlib.h> struct item {     int ref_num,minutes,cost_per_min;     float total_weight; }; // you need 3 more of these int compare_field1 ( const void *a, const void *b ) {     const struct item *pa = a;     const struct item *pb = b;     if ( pa->ref_num < pb->ref_num ) return -1;     if ( pa->ref_num > pb->ref_num ) return +1;     return 0; } int main ( ) {     struct item items[10];     qsort( items, 10, sizeof(struct item), compare_field1 );     return 0; }```
> void recorder( struct item item_array[], int num_items, int sort_field);
All this needs is 4 if statements (testing sort_field) to decide which sort function to call.