Loourr
Loourr

Reputation: 5125

memory error with heap-sort C++

So I have written a heap-sort program in C++ which takes in an array of doubles and the size of the array and then sorts it. The program works however when I attempt to pass it arrays larger then 1000 I get "Bus error: 10" I think this has to do with how memory is being allocated, however I can not seem to find a solution.

    #ifndef _HEAPSORT_
    #define _HEAPSORT_

void Heapsort(double arrayToSort[], int sizeOfArray);

void Heapsort(double arrayToSort[], int sizeOfArray)
{

//      Building Heap:
// ==========================

int halfSize = sizeOfArray-1 / 2;

for(int i = halfSize; i >= 0; i--){
    double temp = arrayToSort[i];
    int I1 = i, I2 = i+i;
    do {
        if( I2 < sizeOfArray - 1 && arrayToSort[I2+1] > arrayToSort[I2] ) { I2++; }
        if( arrayToSort[I2] > temp ){
            arrayToSort[I1] = arrayToSort[I2];
            I1 = I2;
            I2 = I1+I1;
        } else {
            I2 = sizeOfArray;
        }
    } while ( I2 < sizeOfArray );
    arrayToSort[I1] = temp;
}

//      Sorting Heap:
// =========================

for(int i = sizeOfArray-1; i >= 2; i--){ // i is the number of still competing elements
    double temp = arrayToSort[i];
    arrayToSort[i] = arrayToSort[0]; // store top of the heap
    int I1 = 0, I2 = 1;
    do {
        if((I2+1) < i && arrayToSort[I2+1] > arrayToSort[I2] ) { I2++; }
        if(arrayToSort[I2] > temp ){
            arrayToSort[I1] = arrayToSort[I2];
            I1 = I2;
            I2 = I1+I1;
        } else {
            I2 = i;
        }
    } while( I2 < i );
    arrayToSort[I1] = temp;

}

double Temp = arrayToSort[1];
arrayToSort[1] = arrayToSort[0];
arrayToSort[0] = Temp;
}

#endif /* _HEAPSORT_ */

Any insight into how I can fix this would be greatly appreciated. Here is the code where I allocate the memory.

#include <iostream>
#include "heapsort.h"
#include "rmaset.h"
#include "ranmar.h"
#include "common.h"


using namespace std;

int main(void)
{
const int size = 1000;
struct Common block;

rmaset(block);

double array[size];

for(int i = 0; i < size; i++){
    array[i] = ranmar(block);
}

Heapsort(array,size);


return 0;
}

This just creates a struct which then gets passed to a function which initializes it and then to another function ranmar which populates it with random numbers. I have checked all other functions thoroughly and am sure that the error is coming from the Heapsort function.

Upvotes: 1

Views: 471

Answers (1)

Blastfurnace
Blastfurnace

Reputation: 18652

In the following line int halfSize = sizeOfArray-1 / 2; the right side is evaluated as sizeOfArray-(1 / 2). The integer division (1 / 2) results in 0 so it initializes halfSize with the value sizeOfArray. You begin the loop off the end of the array. I think you meant to do (sizeOfArray-1) / 2 instead.

Upvotes: 2

Related Questions