-1

Below is the code I am trying to run, I keep getting the error Segmentation fault. Added Compare. In the below program I need to consider an array of 5000000 or less(this is n) numbers and implement quicksort on those numbers.

int compare (const void * a, const void * b)
{
  const double *da = (const double *) a;
  const double *db = (const double *) b;

  return (*da > *db) - (*da < *db);
  }
int main(){

int n = rand()% 5000000;
double arr[n];
for (int i=0; i<n; i++)
{
    arr[i] = (double)rand();
}
qsort(arr,n, sizeof(double), compare);
 for (int  i=0;i<n;i++){
     cout<<arr[i]<<"\n";
 }
     return 0;
 }
KSK
  • 106
  • 1
  • 8

3 Answers3

2

1) rand usually cannot generate numbers that large. It is commongly capped around 32k

2) double arr[n]; is not legal if n is not a compile-time constant. You are probably using unportable compiler extention.

3) Stack space (where arr resides) is usually very limited. I doubt it can accomodate so much data which is the reason to crash.

Revolver_Ocelot
  • 8,609
  • 3
  • 30
  • 48
1

The problem is that with the double arr[n] syntax you are allocating the array on the stack.

Now, the stack is a limited resource, and n can grow up to almost 5 megabytes, which is way beyond the normal size of the stack

You should allocate the array on the heap with

double * arr = new double[n];

and then free it at the end of the function with

delete[] arr;
Ed Heal
  • 59,252
  • 17
  • 87
  • 127
miniBill
  • 1,743
  • 17
  • 41
0

Sorry this is a very partial answer but I can't add comments (low reputation...) Still, there should be a RAND_MAX value defined in stdlib (0x7FFF in my case) So to my understanding rand() returns a value between 0 and 32767. If you want a value between 0 and 5000000 you can try

unsigned int n = ((double)rand()/RAND_MAX) * 5000000;
double * arr = new double[n];
...
delete[] arr;

Also, check that your compare structure is a strict comparator.

Hope it helps

Aname
  • 515
  • 4
  • 16