Programming in C

(Barry) #1

146 Chapter 8 Working with Functions


Program 8.12 Output
The array before the sort:
34 -5 6 0 12 100 56 22 44 -3 -9 12 17 22 6 11

The array after the sort:
-9 -5 -3 0 6 6 11 12 12 17 22 22 34 44 56 100

The sortfunction implements the algorithm as a set of nested forloops.The outer-
most loop sequences through the array from the first element through the next-to-last
element (a[n-2]). For each such element, a second forloop is entered, which starts
from the element after the one currently selected by the outer loop and ranges through
the last element of the array.
If the elements are out of order (that is, if a[i]is greater than a[j]), the elements are
switched.The variable tempis used as a temporary storage place while the switch is
being made.
When both forloops are finished, the array has been sorted into ascending order.
Execution of the function is then complete.
In the mainroutine,arrayis defined and initialized to 16 integer values.The pro-
gram then displays the values of the array at the terminal and proceeds to call the sort
function, passing as arguments arrayand 16 , the number of elements in array. After the
function returns, the program once again displays the values contained in array. As you
can see from the output, the function successfully sorted the array into ascending order.
The sort function shown in Program 8.12 is fairly simple.The price that must be paid
for such a simplistic approach is one of execution time. If you have to sort an extremely
large array of values (arrays containing thousands of elements, for example), the sort rou-
tine as you have implemented it here could take a considerable amount of execution
time. If this happened, you would have to resort to one of the more sophisticated algo-
rithms.The Art of Computer Programming,Volume 3, Sorting and Searching(Donald E.
Knuth, Addison-Wesley) is a classic reference source for such algorithms.^2

Multidimensional Arrays


A multidimensional array element can be passed to a function just as any ordinary vari-
able or single-dimensional array element can. So the statement
squareRoot (matrix[i][j]);
calls the squareRootfunction, passing the value contained in matrix[i][j]as the argu-
ment.

2.There is also a function called qsortin the standard C library that can be used to sort an array
containing any data type. However, before you use it, you need to understand pointers to func-
tions, which are discussed in Chapter 11.
Free download pdf