-4

I am implementing a basic bucket sort algorithm. The main.cpp file is the driving program, sort.h stores the function declarations and bs.cpp is the algorithm implementation.

main.cpp

case 0: bucketSort(arr, n); break;

sort.h

void bucketSort(int* arr, int n);

bs.cpp

#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <algorithm>
#include <vector>
#include <sort.h>

using namespace std;

// function to sort arr[] of size n using bucket sort
void bucketSort(float arr[], int n)
{
  vector<float> b[n];

  // put elements in different buckets
  for (int i=0; i<n; i++)
  {
    int x = n*arr[i];
    b[x].push_back(arr[i]);
  }

  // sort individual vectors
  for (int i=0; i<n; i++)
  {
    sort(b[i].begin(), b[i].end());
  }

  int index = 0;

  for (int i = 0; i < n; i++)
  {
    while (!b[i].empty())
    {
      arr[index++] = *(b[i].begin());
      b[i].erase(b[i].begin());
    }
  }
}

When I compile, I receive error:

main.o: In function `main':
main.cpp:(.text+0x1d8): undefined reference to `bucketSort(int*, int)'
collect2: error: ld returned 1 exit status
make: *** [main.exe] Error 1

Not sure why it is coming back as undefined.

drad02
  • 1
  • 5
    Look at what you have in `sort.h`, and look at your actual function. Keep staring at both, until you see the big, honking, glaring difference. You really don't see the two completely different function declaration and definition? – Sam Varshavchik Mar 11 '20 at 02:22
  • 2
    Side note unrelated to your problem: `b[n]` is not a good thing to do. Instead you should probably be using a nested `std::vector`. –  Mar 11 '20 at 02:28
  • See https://stackoverflow.com/q/57367473/10957435 for more information. –  Mar 11 '20 at 02:32

1 Answers1

2

You forward declare void bucketSort(int* arr, int n) in sort.h, but you never define it. Rather, in bs.cpp, you define the function void bucketSort(float*, int n).

Your code compiles fine, but the linker ultimately complains that it cannot find a suitable definition of bucketSort. You'll need to rectify the discrepancy between your declaration's signature and your attempted definition.

Brian61354270
  • 8,690
  • 4
  • 21
  • 43