08.01.2023 Views

Learn to Program with C_ Learn to Program using the Popular C Programming Language ( PDFDrive )

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 10 ■ Structures

Given the previous data, the call

search("Singh, Sandy", pupil, 4)

will return 2, and the following call will return -1:

search("Layne, Sandy", pupil, 4)

10.5 Sort an Array of Structure

Suppose we want the list of students in alphabetical order by name. It will be required to sort the

array pupil. The following function uses an insertion sort to do the job. The process is identical to

sorting an int array, say, except that the name field is used to govern the sorting.

void sort(Student list[], int n) {

//sort list[0] to list[n-1] by name using an insertion sort

Student temp;

int k;

for (int h = 1; h < n; h++) {

Student temp = list[h];

k = h - 1;

while (k >= 0 && strcmp(temp.name, list[k].name) < 0) {

list[k + 1] = list[k];

k = k - 1;

}

}

list[k + 1] = temp;

} //end sort

Observe this statement:

list[k + 1] = list[k];

This assigns all the fields of list[k] to list[k+1].

If we want to sort the students in order by age, all we need to change is the while condition.

To sort in ascending order, we write this:

while (k >= 0 && temp.age < list[k].age)

//move smaller numbers to the left

To sort in descending order, we write this:

while (k >= 0 && temp.age > list[k].age)

//move bigger numbers to the left

287

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!