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

(Romina) #1
completion of the program.

Here is the swapping of the variables inside the inner loop:


temp = nums[inner];
nums[inner] = nums[outer];
nums[outer] = temp;

In other words, if a swap needs to take place (the first of the two values being compared is higher
than the second of the two values), the program must swap nums[inner] with nums[outer].


You might wonder why an extra variable, temp, was needed to swap two variables’ values. A
natural (and incorrect) tendency when swapping two variables might be this:


Click here to view code image


nums[inner] = nums[outer]; /* Does NOT swap the */
nums[outer] = nums[inner]; /* two values */

The first assignment wipes out the value of nums[inner] so that the second assignment has nothing
to assign. Therefore, a third variable is required to swap any two variables.


Tip

If you wanted to sort the list in descending order, you would only have to change the
less-than sign (<) to a greater-than sign (>) right before the swapping code.

If you wanted to alphabetize a list of characters, you could do so by testing and swapping character
array values, just as you’ve done here. In Chapter 25, “Arrays and Pointers,” you learn how to store
lists of string data that you can sort.


Faster Searches


Sometimes sorting data speeds your data searching. In the last chapter, you saw a program that
searched a customer ID array for a matching user’s value.


If a match was found, a corresponding customer balance (in another array) was used for a credit
check. The customer ID values were not stored in any order.


The possibility arose that the user’s entered customer ID might not have been found. Perhaps the user
entered the customer ID incorrectly, or the customer ID was not stored in the array. Every element in
the entire customer ID array had to be searched before the programmer could realize that the customer
ID was not going to be found.


However, if the arrays were sorted in customer ID order before the search began, the program would
not always have to look at each array element before deciding that a match couldn’t be made. If the
customer ID array were sorted and the user’s customer ID were passed when looking through a
search, the program would know right then that a match would not be found. Consider the following
list of unsorted customer IDs:

Free download pdf