473,883 Members | 1,652 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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

Feb 26 '06
25 11408
Flash Gordon <sp**@flash-gordon.me.uk> writes:
[...]
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.


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) ks***@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.
Feb 26 '06 #11
On 2006-02-26, Keith Thompson <ks***@mib.or g> wrote:
"Allie" <fa**********@g mail.com> writes:
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!


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.


or "book" is a pointer and "n" is the number of entries in the array it
points at the first element of.
Feb 26 '06 #12
Keith Thompson <ks***@mib.or g> writes:
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.


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
Feb 27 '06 #13
Jordan Abel <ra*******@gmai l.com> writes:
On 2006-02-26, Keith Thompson <ks***@mib.or g> wrote:
"Allie" <fa**********@g mail.com> writes:
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!


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.


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


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

--
Keith Thompson (The_Other_Keit h) ks***@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.
Feb 27 '06 #14
Ben Pfaff <bl*@cs.stanfor d.edu> writes:
Keith Thompson <ks***@mib.or g> writes:
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.


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.


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) ks***@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.
Feb 27 '06 #15
Keith Thompson wrote:
Flash Gordon <sp**@flash-gordon.me.uk> writes:
[...]
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.


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


<snip>

Yes, I know. I even said in the text you snipped, "Unless you have
specific reason not to I would suggest looking up qsort in your C text
book." I went on to say, still before the bit you snipped, "... so if
you need to implement a sort algorithm (I'm guessing that is your
assignment and your reason for not using qsort) ..."

Personally I have never bothered implementing a sort algorithm myself
and probably never will. If I need something better than qsort I'll ask
experts and then use an implementation written by someone else.
--
Flash Gordon, living in interesting times.
Web site - http://home.flash-gordon.me.uk/
comp.lang.c posting guidelines and intro:
http://clc-wiki.net/wiki/Intro_to_clc
Feb 27 '06 #16
Flash Gordon <sp**@flash-gordon.me.uk> writes:
Keith Thompson wrote:
Flash Gordon <sp**@flash-gordon.me.uk> writes:
[...]
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.

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


<snip>

Yes, I know. I even said in the text you snipped, "Unless you have
specific reason not to I would suggest looking up qsort in your C text
book." I went on to say, still before the bit you snipped, "... so if
you need to implement a sort algorithm (I'm guessing that is your
assignment and your reason for not using qsort) ..."


So you did. My apologies for not reading carefully enough.

--
Keith Thompson (The_Other_Keit h) ks***@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.
Feb 27 '06 #17
Ben Pfaff wrote:
Keith Thompson <ks***@mib.or g> writes:
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.


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.


Another possibility is operator malfunction, making the other
malfunctions more or less moot. Many of us are already pushing our
MTBF values.

--
"If you want to post a followup via groups.google.c om, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
More details at: <http://cfaj.freeshell. org/google/>
Also see <http://www.safalra.com/special/googlegroupsrep ly/>
Feb 27 '06 #18
Allie said:
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 );


What I wrote was based on the information you gave me. If you gave me the
wrong information, that is your lookout, not mine.

Incidentally, you have misquoted me. I most certainly did not write:

sizeof( book ) / sizeof (book[0] )

If you wish to become a successful programmer, you will need to develop a
more pedantic approach with regard to accuracy, precision, and correctness.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Feb 27 '06 #19

CBFalconer wrote:
Many of us are already pushing our MTBF values.


Gather ye rosebuds while ye may.

Feb 27 '06 #20

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
3272
by: Federico G. Babelis | last post by:
Hi All: I have this line of code, but the syntax check in VB.NET 2003 and also in VB.NET 2005 Beta 2 shows as unknown: Dim local4 As Byte Fixed(local4 = AddressOf dest(offset)) CType(local4, Short) = CType(src, Short)
7
10093
by: Foodbank | last post by:
Hi everyone. I'm having trouble with this radix sorting program. I've gotten some of it coded except for the actual sorting :( The book I'm teaching myself with (Data Structures Using C and C++) just doesn't explain things good at all and the tutorials I've viewed don't really explain least significant digit first sorting or show examples, which would be most helpful. I've commented the section where I know that the iteration of the...
5
2538
by: DKC | last post by:
Hi, Using VB.NET. I have a datagrid having a strongly typed array of objects as its data source. The data from the array of objects is displayed by means of a table style, which is fine, but I cannot sort the data when I click on the column header. I have set the tablestype.allowsorting = true, but this has no effect.
0
3249
by: Brian Henry | last post by:
Here is another virtual mode example for the .NET 2.0 framework while working with the list view. Since you can not access the items collection of the list view you need to do sorting another way... here is my code on how I did it to help anyone starting out get an idea of how to use virtual mode in ..NET 2.0 Imports CrystalDecisions.CrystalReports.Engine Imports CrystalDecisions.Shared
2
945
by: Allie | last post by:
How would I go about sorting this structure by title? typedef struct { char author; char title; char code; int hold; int loan; } LIBRARY;
1
7202
KevinADC
by: KevinADC | last post by:
Introduction In part one we discussed the default sort function. In part two we will discuss more advanced techniques you can use to sort data. Some of the techniques might introduce unfamiliar methods or syntax to a less experienced perl coder. I will post links to online resources you can read if necessary. Experienced perl coders might find nothing new or useful contained in this article. Short Review In part one I showed you some...
12
9803
by: Justin | last post by:
Ok, I give up. I can't seem to construct a decent (productive) way of sorting my arraylist. I have a structure of two elements: Structure TabStructure Dim TabName As String Dim FullFilePath As String End Structure
5
3195
by: lemlimlee | last post by:
hello, this is the task i need to do: For this task, you are to develop a Java program that allows a user to search or sort an array of numbers using an algorithm that the user chooses. The search algorithms that can be used are Linear Search and Binary Search. The sorting algorithms are bubble, selection and Insertion sort. First, the user is asked whether he/she wants to perform a search option, a sort operation, or exit the program. If...
5
4968
by: jrod11 | last post by:
hi, I found a jquery html table sorting code i have implemented. I am trying to figure out how to edit how many colums there are, but every time i remove code that I think controls how many colums there are, it crashes. There are currently 6 columns, and I only want 4. How do I remove the last two (discount and date)? Here is a link: http://www.jaredmoore.com/tablesorter/docs/salestable.html Here is some jquery js that I think...
0
9932
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9777
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
11109
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10405
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9558
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7957
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7114
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
2
4198
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3226
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.