From the course: Advanced C Programming: Optimize Performance and Efficiency

Unlock the full course today

Join today to access over 24,500 courses taught by industry experts.

Solution: Sort an array of structures

Solution: Sort an array of structures

(upbeat music) - [Instructor] For my solution, I combined exercises from two earlier movies. One was on presetting structure array elements. The other was on sorting an array. So the sort routine goes in this code from lines 29 through 40. It contain two nested loops. One using the variable outer, the other using variable inner. Line 33 compares the temp member of two structure array elements. If the temperature is greater, it needs to be swapped to a later position in the array. That swap takes place at lines 35, 36, and 37. The t variable temporarily holds structures. It's declared at line 18. You see that it's the same structure type as the array. The key to remember when sorting an array of structures is that you don't need to swap each structure members. Simply swap the structure array elements, which is shown here at lines 35, 36, and 37. Build and run. And it works.

Contents