Sorting Array of Structures

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Allie

    #1

    Sorting Array of Structures

    How would I go about sorting this structure by title?

    typedef struct {
    char author[40];
    char title[40];
    char code[4];
    int hold;
    int loan;
    } LIBRARY;

    LIBRARY book[N];


    This is what I've written:

    void sortbytitle( LIBRARY *b, int n ) { /* n = number of books in stock
    */
    LIBRARY temp[N];
    int i;

    for( i = 0; i < n; i++ ) {
    if( strcmp( b[i].title, b[i + 1].title ) > 0 ) {
    temp[i] = b[i];
    b[i] = b[i + 1];
    b[i + 1] = temp[i];
    }
    }

    return;
    }

    I get no errors or warnings when I compile using Bloodshed Dev-C++.
    However, my output then looks like this:
    AUTHOR TITLE CODE #COPY #BORR #AVAIL
    Golumbic Graph Theory G01 5 2 3
    Jacobs Database Logic J01 3 1 2
    Kanter Management Information K01 8 1 7
    Kuo Numerical Methods K02 2 0 2
    Habermann Operating Systems H01 10 5 5
    Schroder C S01 7 2 5
    Herzog Computing Structures H03 10 7 3
    Holub Compiler Design H05 11 8 3
    Galvin Operating Systems G02 15 2 13
    Lane Data Communications L01 20 3 17
    Kleinrock Queueing Systems K03 14 0 14
    Kindred Data Systems K04 2 0 2
    Horowitz Programming Languages H06 16 10 6

    (Original output, before sort is called:
    AUTHOR TITLE CODE #COPY #BORR #AVAIL
    Habermann Operating Systems H01 10 5 5
    Golumbic Graph Theory G01 5 2 3
    Jacobs Database Logic J01 3 1 2
    Kanter Management Information K01 8 1 7
    Kuo Numerical Methods K02 2 0 2
    Hughs Structured Programming H02 4 4 0
    Schroder C S01 7 2 5
    Herzog Computing Structures H03 10 7 3
    Hunter Understanding C H04 6 6 0
    Holub Compiler Design H05 11 8 3
    Galvin Operating Systems G02 15 2 13
    Lane Data Communications L01 20 3 17
    Kleinrock Queueing Systems K03 14 0 14
    Kindred Data Systems K04 2 0 2
    Mano Computer Architecture M01 2 2 0
    Horowitz Programming Languages H06 16 10 6

    The sortbytitle() function is used in conjunction with
    printbyavail(). .. which explains the three missing books in the output
    produced by sortybytitle(). )

    The titles aren't sorted properly! What am I doing wrong?

    Thank you muchly :)

    --Allie

  • Richard Heathfield

    #2
    Re: Sorting Array of Structures

    Allie said:
    [color=blue]
    > How would I go about sorting this structure by title?
    >
    > typedef struct {
    > char author[40];
    > char title[40];
    > char code[4];
    > int hold;
    > int loan;
    > } LIBRARY;
    >
    > LIBRARY book[N];[/color]

    #include <string.h>
    #include <stdlib.h>

    int complib(const void *vp1, const void *vp2)
    {
    const LIBRARY *p1 = vp1;
    const LIBRARY *p2 = vp2;
    return strcmp(p1->title, p2->title);
    }

    int main(void)
    {
    getyourdatainto thearray();

    qsort(book, sizeof book / sizeof book[0], sizeof book[0], complib);

    printyourdata() ;

    return 0;
    }


    --
    Richard Heathfield
    "Usenet is a strange place" - dmr 29/7/1999

    email: rjh at above domain (but drop the www, obviously)

    Comment

    • Vladimir S. Oka

      #3
      Re: Sorting Array of Structures

      Allie wrote:
      [color=blue]
      > How would I go about sorting this structure by title?
      >
      > typedef struct {
      > char author[40];
      > char title[40];
      > char code[4];
      > int hold;
      > int loan;
      > } LIBRARY;
      >
      > LIBRARY book[N];
      >[/color]

      It may be easiest to use `qsort` function. Look it up.

      --
      BR, Vladimir

      Man is a military animal,
      Glories in gunpowder, and loves parade.
      -- P.J. Bailey

      Comment

      • Allie

        #4
        Re: Sorting Array of Structures

        Thanks for your response! :)

        I get this as output now:

        AUTHOR TITLE CODE #COPY #BORR #AVAIL
        Schroder C S01 7 2 5
        Holub Compiler Design H05 11 8 3
        Herzog Computing Structures H03 10 7 3
        Lane Data Communications L01 20 3 17
        Kindred Data Systems K04 2 0 2
        Jacobs Database Logic J01 3 1 2

        It's missing 8 books o_O

        --Allie

        Comment

        • Allie

          #5
          Re: Sorting Array of Structures

          > It's missing 8 books o_O

          ....Or seven, rather.

          Comment

          • Alesak

            #6
            Re: Sorting Array of Structures

            That looks to me like a really naive code.

            1.) the cycle will reach behind the buffer in it's last leap

            2.) the algorithm seems to me like a one half of bubblesort, but I
            cannot imagine, why you have your "temp" as a buffer, the other thing
            is that assigning structure variable to other structure variable does a
            blasphemous plenty of memory copying (and I do believe that true C-man
            avoids that). The right way to sort array of structures is to sort an
            array of pointers. And much, much better than (even not spoilt)
            bubblesort is to use library func, like that:

            #include <stdlib.h>
            #include <string.h>

            typedef struct {
            char author[40];
            char title[40];
            char code[4];
            int hold;
            int loan;

            } LIBRARY;

            static int cmplib (const void *a, const void *b)
            {
            return (strcmp (((LIBRARY*)a)->title, ((LIBRARY*)b)->title));
            }
            void do_sort (LIBRARY **l, int count)
            {
            qsort (l, count, sizeof (LIBRARY*), cmplib);
            }

            Comment

            • Allie

              #7
              Re: Sorting Array of Structures

              To Richard: qsort( book, n, sizeof( book[0] ), comptitle ); gives me
              the right output. You had written qsort( book, sizeof( book ) / sizeof
              (book[0] ), sizeof book[0], comptitle ); Thanks for your help!

              To Alesak: I'm not a very seasoned programmer. In fact, I'm just a
              student still learning the C language. The last time I touched C was
              nine months ago... so I'm a little rusty. But I appreciate any and all
              help I get (because sometimes I don't know what I'm doing wrong so that
              I can't look up the solution to my problem). So thank you :)

              Comment

              • Default User

                #8
                Re: Sorting Array of Structures

                Allie wrote:
                [color=blue]
                > Thanks for your response! :)
                >
                > I get this as output now:[/color]


                How can we fix code we can't see? Post a complete, minimal program,
                plus the data.

                Also, read the information below.


                Brian
                --
                Please quote enough of the previous message for context. To do so from
                Google, click "show options" and use the Reply shown in the expanded
                header.

                Comment

                • Flash Gordon

                  #9
                  Re: Sorting Array of Structures

                  Allie wrote:[color=blue]
                  > How would I go about sorting this structure by title?[/color]

                  Unless you have specific reason not to I would suggest looking up qsort
                  in your C text book.
                  [color=blue]
                  > typedef struct {
                  > char author[40];
                  > char title[40];
                  > char code[4];
                  > int hold;
                  > int loan;
                  > } LIBRARY;
                  >
                  > LIBRARY book[N];
                  >
                  >
                  > This is what I've written:
                  >
                  > void sortbytitle( LIBRARY *b, int n ) { /* n = number of books in stock
                  > */
                  > LIBRARY temp[N];[/color]

                  Why make this an array? You only use each element once.
                  LIBRARY temp;
                  [color=blue]
                  > int i;
                  >
                  > for( i = 0; i < n; i++ ) {[/color]

                  You are doing one too many elements. There is no element after the last
                  element for you to compare against and possibly swap with!
                  for( i = 0; i < n-1; i++ ) {

                  [color=blue]
                  > if( strcmp( b[i].title, b[i + 1].title ) > 0 ) {
                  > temp[i] = b[i];[/color]

                  temp = b[i];
                  [color=blue]
                  > b[i] = b[i + 1];
                  > b[i + 1] = temp[i];[/color]

                  b[i+1] = temp;
                  [color=blue]
                  > }
                  > }
                  >
                  > return;
                  > }
                  >
                  > I get no errors or warnings when I compile using Bloodshed Dev-C++.[/color]

                  <snip>

                  Not surprising, your only C error is going off the end of your array,
                  and compilers don't have to complain about that.

                  You also have a major algorithm error, but we only do C here not
                  algorithms. I believe comp.programmin g does algorithms, so if you need
                  to implement a sort algorithm (I'm guessing that is your assignment and
                  your reason for not using qsort) then that is the place to ask.

                  However, here are some hint for you:

                  How can you move an element from position 2 to position 0? Your
                  implementation can at most move it to position 1.

                  Google for "bubble sort" since I think that is what you are trying to
                  implement and it is also nice and easy to understand. There are more
                  efficient algorithms, but they are harder to understand and you should
                  start with the simplest approach.
                  --
                  Flash Gordon, living in interesting times.
                  Web site - http://home.flash-gordon.me.uk/
                  comp.lang.c posting guidelines and intro:

                  Comment

                  • Keith Thompson

                    #10
                    Re: Sorting Array of Structures

                    "Allie" <fakeprogress@g mail.com> writes:[color=blue]
                    > To Richard: qsort( book, n, sizeof( book[0] ), comptitle ); gives me
                    > the right output. You had written qsort( book, sizeof( book ) / sizeof
                    > (book[0] ), sizeof book[0], comptitle ); Thanks for your help![/color]

                    Richard's sizeof(book) / sizeof(book[0] assumes you want to sort the
                    entire array; apparently you just want to sort the first n entries.

                    --
                    Keith Thompson (The_Other_Keit h) kst-u@mib.org <http://www.ghoti.net/~kst>
                    San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
                    We must do something. This is something. Therefore, we must do this.

                    Comment

                    • Keith Thompson

                      #11
                      Re: Sorting Array of Structures

                      Flash Gordon <spam@flash-gordon.me.uk> writes:
                      [...][color=blue]
                      > Google for "bubble sort" since I think that is what you are trying to
                      > implement and it is also nice and easy to understand. There are more
                      > efficient algorithms, but they are harder to understand and you should
                      > start with the simplest approach.[/color]

                      Bubble sort is a decent good starting point if you're trying to
                      understand the process of sorting; it's fairly simple, and it's
                      relatively easy to understand how it works. But it also happens to be
                      one of the *least* efficient sorting algorithms, at least among those
                      that weren't deliberately designed for inefficiency.[*]

                      But the simplest way to sort something in C is to use the predefined
                      qsort() function. It has the advantage that the algorithm itself is
                      likely to be as efficient as possible, or nearly so. The
                      disadvantages are that the interface imposes some overhead (an
                      indirect function call for each comparison), and you can't necessarily
                      see the algorithm (which isn't necessarily Quicksort).
                      [*]
                      One of my favorite "pessimal" sorting algorithms is Permutation
                      Sort. Starting with an array of elements, generate all possible
                      permutations. Check each permutation to see whether it happens to be
                      sorted. (An optimized version allows you to stop at this point;
                      otherwise you can save the sorted permutation and continue to generate
                      all the others.)

                      Another really bad technique is Miracle Sort (which, strictly
                      speaking, doesn't qualify as an algorithm). Start with an array of
                      elements. Check whether it's sorted. If it is, you're done.
                      Otherwise, wait a while and check again. Pray for cosmic rays or
                      other fortuitous memory faults.

                      --
                      Keith Thompson (The_Other_Keit h) kst-u@mib.org <http://www.ghoti.net/~kst>
                      San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
                      We must do something. This is something. Therefore, we must do this.

                      Comment

                      • Jordan Abel

                        #12
                        Re: Sorting Array of Structures

                        On 2006-02-26, Keith Thompson <kst-u@mib.org> wrote:[color=blue]
                        > "Allie" <fakeprogress@g mail.com> writes:[color=green]
                        >> To Richard: qsort( book, n, sizeof( book[0] ), comptitle ); gives me
                        >> the right output. You had written qsort( book, sizeof( book ) / sizeof
                        >> (book[0] ), sizeof book[0], comptitle ); Thanks for your help![/color]
                        >
                        > Richard's sizeof(book) / sizeof(book[0] assumes you want to sort the
                        > entire array; apparently you just want to sort the first n entries.[/color]

                        or "book" is a pointer and "n" is the number of entries in the array it
                        points at the first element of.

                        Comment

                        • Ben Pfaff

                          #13
                          Re: Sorting Array of Structures

                          Keith Thompson <kst-u@mib.org> writes:
                          [color=blue]
                          > Another really bad technique is Miracle Sort (which, strictly
                          > speaking, doesn't qualify as an algorithm). Start with an array of
                          > elements. Check whether it's sorted. If it is, you're done.
                          > Otherwise, wait a while and check again. Pray for cosmic rays or
                          > other fortuitous memory faults.[/color]

                          My guess is that it's more likely for the processor to
                          malfunction and decide that the data is sorted, when it really is
                          not,than it is for the malfunction to change the data to sorted
                          order.
                          --
                          "I ran it on my DeathStation 9000 and demons flew out of my nose." --Kaz

                          Comment

                          • Keith Thompson

                            #14
                            Re: Sorting Array of Structures

                            Jordan Abel <random832@gmai l.com> writes:[color=blue]
                            > On 2006-02-26, Keith Thompson <kst-u@mib.org> wrote:[color=green]
                            >> "Allie" <fakeprogress@g mail.com> writes:[color=darkred]
                            >>> To Richard: qsort( book, n, sizeof( book[0] ), comptitle ); gives me
                            >>> the right output. You had written qsort( book, sizeof( book ) / sizeof
                            >>> (book[0] ), sizeof book[0], comptitle ); Thanks for your help![/color]
                            >>
                            >> Richard's sizeof(book) / sizeof(book[0] assumes you want to sort the
                            >> entire array; apparently you just want to sort the first n entries.[/color]
                            >
                            > or "book" is a pointer and "n" is the number of entries in the array it
                            > points at the first element of.[/color]

                            In the original code (since snipped), "book" was an array.

                            --
                            Keith Thompson (The_Other_Keit h) kst-u@mib.org <http://www.ghoti.net/~kst>
                            San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
                            We must do something. This is something. Therefore, we must do this.

                            Comment

                            • Keith Thompson

                              #15
                              Re: Sorting Array of Structures

                              Ben Pfaff <blp@cs.stanfor d.edu> writes:[color=blue]
                              > Keith Thompson <kst-u@mib.org> writes:[color=green]
                              >> Another really bad technique is Miracle Sort (which, strictly
                              >> speaking, doesn't qualify as an algorithm). Start with an array of
                              >> elements. Check whether it's sorted. If it is, you're done.
                              >> Otherwise, wait a while and check again. Pray for cosmic rays or
                              >> other fortuitous memory faults.[/color]
                              >
                              > My guess is that it's more likely for the processor to
                              > malfunction and decide that the data is sorted, when it really is
                              > not,than it is for the malfunction to change the data to sorted
                              > order.[/color]

                              Not if the technique lives up to its name.

                              (Amusing typo: I initially left the 'v' out of "lives".)

                              --
                              Keith Thompson (The_Other_Keit h) kst-u@mib.org <http://www.ghoti.net/~kst>
                              San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
                              We must do something. This is something. Therefore, we must do this.

                              Comment

                              Working...