I tried to program a merge sort function using only static arrays and of course I have an incomprehensible error.
So the first question is that when I compile my program it gives me a multiple definition error on line 9 of that code:
#include <cmath>
#include "include\sort.h"
/*
Theses fonctions accept only arrays of unsigned short int with a length in unsigned int
*/
unsigned short int* sortByFusion(unsigned short int arr[]) { // HERE !!!!!!!!
const unsigned int arrSize = sizeof(arr)/sizeof(unsigned short int);
if (arrSize <= 1) {return arr;}
/*
Declarations and initializations of the two half array
*/
const unsigned int arrLeftSize = static_cast<unsigned int>(floor(arrSize/2));
const unsigned int arrRightSize = static_cast<unsigned int>(arrSize - arrLeftSize);
unsigned short int arrLeft[arrLeftSize];
unsigned short int arrRight[arrRightSize];
for (unsigned int i = 0; i < arrLeftSize; i ++)
arrLeft[i] = arr[i];
for (unsigned int i = 0; i < arrRightSize; i ++)
arrRight[i] = arr[i + arrLeftSize];
/*
Sort the two arrays
*/
for (unsigned int i = 0; i < arrLeftSize; i ++)
arrLeft[i] = *(sortByFusion(arrLeft) + i);
for (unsigned int i = 0; i < arrRightSize; i ++)
arrRight[i] = *(sortByFusion(arrRight) + i);
/*
And fusion them
*/
unsigned int i(0), j(0);
for (unsigned int k = 0; k < arrSize; k ++) {
if (i >= arrLeftSize) {arr[k] = arrRight[j]; j ++;} //That line
else if (j >= arrRightSize) {arr[k] = arrLeft[i]; i ++;} //And that line are here to avoid segmentation fault
else {
if (arrLeft[i] <= arrRight[j]) {arr[k] = arrLeft[i]; i ++;}
else {arr[k] = arrRight[j]; j ++;}
}
}
return arr;
}
What did I do wrong? I tried to put some ifndef define endif but it did nothing more. It seems that everybody has a problem with multiple definition always a bit different on this forum.
Secondly, I used some static_cast but why does floor return a double when we pass a double as argument? Logically, it should give us an integer (the floor of a number is always an integer ...)?
For the compiler, it is GNU GCC, but I don't know how to find its version. And I work with Code::Blocks.
And this is the header file :
#ifndef SORT_H_INCLUDED
#define SORT_H_INCLUDED
unsigned short int* sortByFusion(unsigned short int arr[]);
#endif // SORT_H_INCLUDED