Reputation: 21
int findMedian (int argc, char** argv){
int temp;
for(int i=0; i<argc; ++i) { /// bubble sort the array
for(int j=i+1; j<argc ; ++j) {
if(argv[i] > argv[j]) {
temp = atoi(argv[i]);
argv[i] = argv[j];
*argv[j] = temp;
}
}
}
int Median;
if(argc %2 == 0){///if is even amount of number, take the mean of middle two number
Median= ((atoi(argv[argc / 2 ])+ atoi(argv[argc / 2 + 1])) /2);
}
else{ /// if is odd amount of number, take the middle number.
Median = atoi(argv[argc / 2 + 1 ]);
}
return Median;
}
My median function will give me a median that is not sorted. anyone know why? Thanks for the help.
Upvotes: 0
Views: 815
Reputation: 3325
1) If you want to sort an array of numbers, you need to convert string (char*) arguments to numbers first. Process argv** string array and convert each char* argument to integer with atoi
, or, better, strtol
function, filling new array of integers.
2) Having array of integers, you can sort them with library qsort
function.
Upvotes: 0
Reputation: 57033
First, you sort pointers to the string representations of numbers instead of numbers. Let's assume that your numbers are integer (since you use atoi
and return an int
). You should allocate an array of integers of the appropriate length, convert the strings into integers with strtol()
in a loop, and store the integers into the array. Now, the data are ready for sorting.
Note 1: Do not use atoi()
for conversion because it cannot tell a true 0 from a non-numeric string - unless you can guarantee that all the strings are valid representations of integer numbers.
Note 2: Since your function is meant to calculate the median of an array of integer numbers, make it take an array of integer numbers as a parameter. Do the conversion elsewhere (in the caller).
Finally, consider using qsort()
instead of manually sorting the array. qsort()
is known to work, unlike your code, and it is on average much faster.
Upvotes: 1
Reputation: 161
If you're going to do a comparison like this, you'll have to do one of the following:
sscanf(argv[i], "%f", ...);
sscanf(argv[j], "%f", ...);
then compare the values from the scanf floats.
strcmp(argv[i], argv[j]);
stricmp(argv[i], argv[j]); // if your compiler requires it.
or some other derivative.
Upvotes: 0