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

(Romina) #1

23. Alphabetizing and Arranging Your Data


In This Chapter


  • Putting your house in order: sorting

  • Conducting faster searches


Sorting is the computer term given to ordering lists of values. Not only must you be able to find data
in arrays, but you often need to arrange array data in a certain order. Computers are perfect for sorting
and alphabetizing data, and arrays provide the vehicles for holding sorted data.


Your programs don’t always hold array data in the order you want to see that data. For example,
students don’t enroll based on alphabetical last name, even though most colleges print lists of students
that way. Therefore, after collecting student data, the school’s computer programs must somehow
arrange that data in last name order for reports.


This chapter explains the easiest of computer sorting techniques, called the bubble sort.


Putting Your House in Order: Sorting


If you want to alphabetize a list of letters or names, or put a list of sales values into ascending order
(ascending means from low to high, and descending means from high to low), you should use a
sorting routine. Of course, the list of values that you sort will be stored in an array because array
values are so easily rearranged by their subscripts.


Think about how you’d put a deck of cards in order if you threw the cards up in the air and let them
fall. You would pick them up, one by one, looking at how the current card fit in with the others in your
hand. Often you would rearrange some cards that you already held. The same type of process is used
for sorting an array; often you have to rearrange values that are in the array.


Several computer methods help in sorting values. This chapter teaches you about the bubble sort. The
bubble sort isn’t extremely efficient compared to other sorts, but it’s the easiest to understand. The
name bubble sort comes from the nature of the sort. During a sort, the lower values “float” up the list
each time a pass is made through the data. Figure 23.1 shows the process of sorting five numbers
using a bubble sort.

Free download pdf