0

I wrote code in C++ in visual studios to try and implement mergesort. Whenever I try to compile it gives the same error, C3681 'merge' identifier not found, which I don't understand what exactly is not being identified. Please help!

#include <iostream> 
#include <limits.h>
using namespace std;
void mergeSort(int A[], int p, int r) {
    int q;
    if (p < r) {
        q = p + (r - 1) / 2;
        mergeSort(A, p, q);
        mergeSort(A, q + 1, r);
        merge(A, p, q, r);
    }
}
void merge(int array[], int p, int q, int r) {
    int a, b, c;
    int m = q - p + 1;
    int n = r - q;
    int* left_array = new int[m + 1];
    int* right_array = new int[n + 1];
    for (int i = 0; i < m; i++) {
        left_array[i] = array[p + 1];
    }
    for (int j = 0; j < n; j++) {
        right_array[j] = array[q + 1 + j];
    }
    left_array[m + 1] = INT_MAX;
    right_array[n + 1] = INT_MAX;
    a = 0;
    b = 0;
    c = 1;
    while (a < m && b < n) {
        if (left_array[a] <= right_array[b]) {
            array[c] = left_array[a];
            a++;
        }
        else {
            array[c] = right_array[b];
            b++;
        }
        c++;
    }
    while (a < m) {
        array[c] = left_array[a];
        a++;
        c++;
    }
    while (b < n) {
        array[c] = left_array[b];
        b++;
        c++;
    }
}
}
int main(int argc, char* argv[]) {
    int A[10] = { 9,8,7,6,5,4,3,2,1,0 };
    mergeSort(A, 0, 9);
}
  • FYI, your `merge` function has the same name as `std::merge`, which you can potentially bring in with `using namespace std;` depending whether or not a particular implementation has `` as a transitive include or whether you include it later. You _shouldn't_ run into problems in this case, but it's a minefield out there. – chris Feb 14 '22 at 05:49
  • Swap the order of declaration. First `merge` then `mergeSort`. – Robert Andrzejuk Feb 14 '22 at 06:53

2 Answers2

1

because c++ is very fussy, it likes to see things in the correct order or at least not be surprised by names it hasn't seen yet. You need to declare merge before you call it.

#include <iostream> 
#include <limits.h>
using namespace std;
void merge(int array[], int p, int q, int r); <<<<=======
void mergeSort(int A[], int p, int r) {
 ......
pm100
  • 48,078
  • 23
  • 82
  • 145
0

Well, maybe this can help you. Implicit function declarations in C Just in my opinion, C++ is drived by C, so sometimes for compatibility reasons, some C syntax is retained.

hucutie
  • 1
  • 2