Question: The language is in C. Please provide codes with explanations. This assignment asks you to write a program that uses qsort (a function provided by
The language is in C. Please provide codes with explanations.
This assignment asks you to write a program that uses qsort (a function provided by C) to sort an array of integers in the ascending order.
You will learn to
Count the number of integers in a file
Allocate memory (an array) to store the integers
Read integers from the file and store them in the array
Call qsort function to sort the integers
Write the sorted array to another file
Release memory
Check memory error using valgrind
The qsort function is a generic function in C for sorting arrays. Please go to the link and read the explanation. For this assignment, you need to understand how to use qsort. You do not need to understand the algorithm. You will learn the algorithm later (after understanding recursion).
| #include | |
| #include | |
| #include | |
| #ifdef TEST_COUNTINT | |
| int countInt(char * filename) | |
| { | |
| // count the number of integers in the file | |
| // Please notice that if a file contains | |
| // 124 378 -56 | |
| // There are three integers: 124, 378, -56 | |
| // DO NOT count individual character '1', '2', '4' ... | |
| // | |
| // If fopen fails, return -1 | |
| // remember to fclose if fopen succeeds | |
| } | |
| #endif | |
| #ifdef TEST_READINT | |
| bool readInt(char* filename, int * intArr, int size) | |
| { | |
| // if fopen fails, return false | |
| // read integers from the file. | |
| // | |
| // | |
| // if the number of integers is different from size (too | |
| // few or too many) return false | |
| // | |
| // if everything is fine, fclose and return true | |
| return true; | |
| } | |
| #endif | |
| #ifdef TEST_COMPAREINT | |
| int compareInt(const void *p1, const void *p2) | |
| { | |
| // needed by qsort | |
| // | |
| // return an integer less than, equal to, or greater than zero if | |
| // the first argument is considered to be respectively less than, | |
| // equal to, or greater than the second. | |
| } | |
| #endif | |
| #ifdef TEST_WRITEINT | |
| bool writeInt(char* filename, int * intArr, int size) | |
| { | |
| // if fopen fails, return false | |
| // write integers to the file. | |
| // one integer per line | |
| // | |
| // fclose and return true | |
| } | |
| #endif |
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
