Thread: Qsort

  1. #1
    Registered User
    Join Date
    Oct 2001
    Posts
    17

    Question 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.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > 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.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. An interesting problem of qsort()
    By meili100 in forum C++ Programming
    Replies: 6
    Last Post: 03-05-2008, 12:09 PM
  2. qsort() in Array of Pointer to String
    By vb.bajpai in forum C Programming
    Replies: 8
    Last Post: 06-16-2007, 04:18 PM
  3. trouble with qsort
    By qubit67 in forum C Programming
    Replies: 5
    Last Post: 04-29-2007, 10:23 PM
  4. Question About Using qsort
    By Zildjian in forum C Programming
    Replies: 3
    Last Post: 11-04-2003, 03:17 PM
  5. C++ link error with qsort
    By bvnorth in forum C++ Programming
    Replies: 7
    Last Post: 10-24-2003, 02:22 AM