Home > Software design >  Sort function is giving error in C code of merge sort
Sort function is giving error in C code of merge sort

Time:12-18

#include <iostream>
using namespace std;
// merging two sorted array

void merge1(int a[], int b[], int m, int n)
{
  int c[m   n];
  for (int i = 0; i < m; i  )
    c[i] = a[i];
  for (int i = 0; i < n; i  )
    c[m   i] = b[i];
  sort(c, c   m   n);
  for (int i = 0; i < (m   n); i  )
    cout << c[i] << " ";
}

int main()
{
  int a[] = {10, 15, 20, 20};
  int b[] = {1, 12};
  merge1(a, b, 4, 2);
}

Error :

error: 'sort' was not declared in this scope; did you mean 'qsort'?
   21 |   sort(c, c   m   n);
      |   ^~~~
      |   qsort

CodePudding user response:

The program works but on higher versions of clang and gcc, which implies a higher version of the standard being required. This problem can be reproduced if you drop the version of the compiler being used. If you drop the compiler version, you will need to include <algorithm> and the program will work fine.

Take a look.

My best guess is either the compiler somehow recognizes the function at compile-time, or the function is visible in higher C standard versions via some hidden includes in the <iostream> or headers that it includes.

You can see a similar story on clang side too.

Notes
  • You need to check the version of the compiler you are using and in general, observe if the function you are using is supported by the standard you are running.
  • Also, please include proper header files when you run something like this.
  • Also, please for crying out loud stop doing using namespace std;. Please.
  •  Tags:  
  • c
  • Related