C Programming Absolute Beginner's Guide (3rd Edition)

(Romina) #1

Keeping arrays sorted is not always easy or efficient. For instance, you don’t want your program
sorting a large array every time you add, change, or delete a value from the array. After storing
several thousand values in an array, sorting the array after adding each value takes too much time,
even for fast computers. Advanced ways of manipulating arrays ensure that you always insert items in
sorted order. (However, such techniques are way beyond the scope of this book.) You’re doing well
without complicating things too much here.


The Absolute Minimum
The goal of this chapter was to familiarize you with the bubble sort method of ordering
and alphabetizing values in arrays. You don’t need any new C commands to sort
values. Sorting is one of the primary array advantages. It shows that arrays are a better
storage method than separately named variables. The array subscripts let you step
through the array and swap values, when needed, to sort the array.
Key concepts from this chapter include:


  • Use an ascending sort when you want to arrange array values from low to high.

  • Use a descending sort when you want to arrange array values from high to low.

  • The nested for loop, such as the one you saw in this chapter, is a perfect statement
    to produce a bubble sort.

  • Don’t swap the values of two variables unless you introduce a third temporary
    variable to hold the in-between value.

  • Sorting routines doesn’t have to be hard; start with the one listed in this chapter, and
    adapt it to your own needs.

  • Don’t forget to keep your arrays sorted. You’ll speed up searching for values.

Free download pdf