0
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.

Spock77
  • 3,256
  • 2
  • 30
  • 39
  • 4
    At least this if statement if(argv[i] > argv[j]) { does not make sense. Ther are compied pointers themselves instead of the pointed values. – Vlad from Moscow Apr 01 '18 at 15:44

3 Answers3

1

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.

DYZ
  • 55,249
  • 10
  • 64
  • 93
0

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.

Nova Ardent
  • 161
  • 1
  • 16
0

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.

Spock77
  • 3,256
  • 2
  • 30
  • 39
  • note that [`atoi` shouldn't be used in serious contexts](https://stackoverflow.com/q/17710018/995714) – phuclv Apr 02 '18 at 01:10
  • Should not, agree. This one is not a serious, I believe (?). Using atoi as in the original code it should be assumed that all input is correct. Suggested "better, strtol". – Spock77 Apr 02 '18 at 01:47