130 Intermediate C Programming
parts: the part before ind1 has been sorted and the part after ind1 has not been sorted. To
sort the second part, we select the smallest inside this part and move it to the beginning of
the second part. Then, ind1 increases, effectively shrinking the second part.
Line 20 initializes minind to ind1. This stores the index of the smallest element seen
so far in the second part of the array. Then, lines 21 to 27 find the index of the smallest
element in the second part of the array. Lines 28 to 32 move the smallest value to the correct
place in the array. This is achieved by swapping the smallest value from its current location
to the correct location. The number of comparisons (line 23) depends on the number of
elements and is independent of the actual values of the elements.
This program uses the same swap function described in Section 4.4. The swap function
is marked static. A static function can be called by functions in the same file only. A static
function is invisible outside this file.
Consider the following example: The input values are 1694, 8137, 609, 7118, 5614, and
8848. The smallest value is the third element (index is 2). The first iteration of ind1 swaps
the first (index is 0) and the third elements and now the array’s elements are 609, 8137,
1694, 7118, 5614, and 8848. The following table shows the array’s elements in each iteration,
just before calling swap:
ind1 minind Sorted Unsorted
0 2 1694 8137 609 7118 5614 8848
1 2 609 8137 1694 7118 5614 8848
2 4 609 1694 8137 7118 5614 8848
3 3 609 1694 5614 7118 8137 8848
4 4 609 1694 5614 7118 8137 8848
5 5 609 1694 5614 7118 8137 8848
This is the sorted array: 609 1694 5614 7118 8137 8848. The main function has a few
places that require explanation:
• This main function stores the data in an array. The size of the array is given by
argv[1].
• Before using argv[1], the program must check that argc is 2. If argc is 1, then
argv[1] does not exist (argv[0] does) and attempting to access argv[1] will crash
the program.
• The program uses strtol to convert argv[1] from a string to an integer.
• The main function must call malloc to allocate heap memory for the array before
reading data from the file.
• The main function must call free to release the heap memory of the array before the
program ends.
/*1
* main . c2
*/3
#in clude < stdio .h >4
#in clude < stdlib .h >5
#in clude < string .h >6
#in clude " mysort .h "7
int main ( i n t argc , char * * argv )8
{9
i f ( argc != 2)10
{11
return EXIT _FAILUR E ;12
}13
int number = strtol ( argv [1] , NULL , 10) ;14