My heap sort keeps on crashing (C++)

Started by
11 comments, last by BitMaster 11 years ago

I made a heapsort today, but when I run it, I always get an error and my compiler aborts the program

Well here is my walkdown algorithm:


template <class DataType>

//HeapWalkDown: Walks down an a node in array

//               (Array, Index of parent of the lowest node, Size of the array, comparison function)
void HeapWalkDown( Array<DataType> &p_array, int p_index, int p_maxIndex, int (*p_compare)(DataType, DataType))
{
	//Keeps track of the current parent index
	int parent = p_index;

	//Keeps track of the current child index
	int child  = p_index * 2;

	//Stores the data that is being walked down into a temporary variable
	DataType temp = p_array[parent];

	//Starts a loop, loops through the tree until the child index is
	//greater then the tree size
	while(child <= p_maxIndex)
	{
		//If the left child is not the last node in the tree, then
		//find out which of the current node's children is the largest
		if(child < p_maxIndex)
		{
			//Compare the left and right child to see which one holds
			//the larger value

		    //           LEFT CHILD        RIGHT CHILD
			if(p_compare(p_array[child], p_array[child + 1]) < 0)
			{
				//If the right child has the larger, then increment the child index
				//because the the index of the right child is always is one larger
				//then the left child
				child++;
			}
		}

		//Now the function knows which child it wants to move upward. It
        //Determines if the child node needs to move upward by comparing
	    //it to the value in the temp variable
        if(p_compare(temp, p_array[child]) < 0)
		{
			//Moves the child upward into the parent index
			p_array[parent] = p_array[child];

			//
			parent = child;
			child *= 2;
		}

		//If no swap is needed
		else
		{
			break;
		}
	}

	//The value in temp is placed into the correct index
	p_array[parent] = temp;
}

and heres the heapsort function:


//Heapsort: Sorts an array into a heap, then turn the heap into a 
//sorted array
template <class DataType>
void Heapsort( Array<DataType> &p_array, int (*p_compare)(DataType, DataType))
{
	//Used to loop through the array
	int index;

	//Keeps track of the size of the array
	int maxIndex = p_array.Size();

	//The index of the last node's parent
	int rightindex = maxIndex/2;

	//Turns the array into a heap by walking down everything to
	//its proper place
	for(index = rightindex; index > 0; index--)
	{
		//Walk everything down, turning the array into a heap
		HeapWalkDown(p_array, index, maxIndex, p_compare);
	}

	//Starts creating a sorted array from the newly formed heap
	while(maxIndex > 0)
	{
		//Swap the root with the last node in the tree
		Swap(p_array[0], p_array[maxIndex - 1]);

		//Decrease the size of the tree
		maxIndex--;

		//Walk Down the top index
		HeapWalkDown(p_array, 1, maxIndex, p_compare);
	}
}




//Swap: Swap a left and right variable around
template <class DataType>
void Swap( DataType& a, DataType& b )
{
    static DataType t;
    t = a;
    a = b;
    b = t;
}



Note they all are in one header file

and here is my source file which demonstrates the sort


#include <iostream>
#include "Array.h"
#include "Heapsort2.h"
#include <stdlib.h>
#include <time.h>
using namespace std;


//Comparison function
int intcompare(int l, int r)
{
	return l - r;
}

int comparereverseint(int l, int r)
{
	return r - l;
}

int comparefloat(float l, float r)
{
	if(l > r)
		return 1;
	if(l < r)
		return -1;
	return 0;
}

//Function automatically prints an array
template <class DataType>
void PrintArray(Array<DataType> p_array)
{
	for(int i = 0; i < p_array.m_size; i++)
	{
		cout << p_array << ", ";
	}
	cout << endl << endl;
}


int main()
{

	//Create two arrays
	Array<int> iarray(16);
	Array<float> farray(16);

	//Seed the random number generator
	srand(time(0));

	//Fills the array with random values
	for(int index = 0; index < 16; index++)
	{
		iarray[index] = rand() % 256;
		farray[index] = (float)(rand() % 256) / 256.0f;
	}

	//Display the Unsorted arrays
	cout << "Unsorted Integer array: " << endl;
	PrintArray(iarray);

    cout << "Unsorted Float array: " << endl;
	PrintArray(farray);

	
	//Sort the arrays
	HeapSort(iarray, intcompare);
	HeapSort(farray, comparefloat);

	
	//Display the sorted arrays
	cout << "Sorted Integer array: " << endl;
	PrintArray(iarray);

	cout << "Sorted Float array: " << endl;
	PrintArray(farray);


	cin.get();
	return 0;
}

any help would be appreciated

Advertisement
First off, read this. After following through with the instructions from the FAQ, feel free to update this post with all the relevant information you omitted the first time ;-)

Wielder of the Sacred Wands
[Work - ArenaNet] [Epoch Language] [Scribblings]

K no problem. Ill look into it and will be back tomorrow.

I haven't looked into your crash problem yet, first a few other observations:

In your Swap method, you made t static. This doesn't really gain you anything, and it takes away the ability to use this in a multi-threaded scenario. I suggest removing the static keyword.

Be careful with the cheap comparison hack of return l - r; It doesn't work in every case, e.g. when r is MIN_INT. The way comparefloat does it is safer.

More commenting isn't always good. Too little is a common problem, but too much can also be a problem. It does depend on the nature of the commenting though. The most important thing to comment is always "Why". Avoid stating the obvious, e.g. "Create two arrays".

This "Array" class seems to be some kind of custom array type with an overloaded [] operator. This is good news as it means that you can add bounds checking to that operator, and hopefully it will find the bug for you. It's almost certainly an out-of-bounds access issue.
Perhaps use asserts for this so that your release build performance isn't affected.
"In order to understand recursion, you must first understand recursion."
My website dedicated to sorting algorithms

What is the error?

alright for some odd reason the image would not upload in photobucket or imageshack so I just compressed it and uploaded it here

http://www.sendspace.com/file/gmyvfc

I looked at that article and im still lost. The compiler only throws that window at me and give me no idea of where it went wrong

You have a memory corruption bug. Can you post the code for Array<>?

Wielder of the Sacred Wands
[Work - ArenaNet] [Epoch Language] [Scribblings]

Here it is:


#pragma once
#include <iostream>
using namespace std;

template <class Datatype>
class Array
{
public:

	//pointer to the array
	Datatype *m_array;

	//the arrays size
	int m_size;

	//the constructor
	Array(int p_size)
	{
		//pointer is used to allocate the specified amount that was passed in
		m_array = new Datatype[p_size];
		//member size variable is now equivalent to the passed in size variable
		m_size = p_size;
	}

	//the destructor
	~Array()
	{
		//deallocates the array and then makes the pointer point to NULL/0
		if(m_array != 0)
		{
			delete[] m_array;
		}
		m_array = 0;
	}

	//the array resize function
	void Resize(int p_size)  //first you gotta pass in the value of the new size you want
	{
		//pointer to the newly allocated array
		Datatype *newarray = new Datatype[p_size];
		if(newarray == 0) //if the newarray points to nothing
		{
			return;  //then exit the function
		}

		int min;
		if(p_size < m_size)
		{
			//if the passed in size is less then the size of the original array
			//than min variable equals the passed in size;
			min = p_size;
		}
		else
		{
			//if the passed in size is greater than or equal to the old array size
			//than min equal m_size
			min = m_size;
		}

		int index; //the iterator for the for loop
		for(index = 0; index < min; index++)
		{
			newarray[index] = m_array[index]; // copying from old array to new array
		}

		m_size = p_size;  //the member size is now updated to reflect the size of the new array

		if(m_array != 0)
		{
			delete[] m_array;
		}
		m_array = newarray;
	}

	Datatype& operator[](int p_index) //this opertor overload allows you to change the the value
	{                                 //of the array at any index by using normal syntax like intarray[5] = 42
		return m_array[p_index];      // rather than intarray.m_array[5] = 42 
	}

	operator Datatype*()    //lets you pass in an array declared in many different types of forms into the function
	{                       //conversion operator overload
		return m_array;
	}

	void Insert(Datatype p_item, int p_index) //pass in the value you want to insert at the location you want
	{
		int index;  //sets up an iterator
		for(index = m_size - 1; index > p_index; index--) //index equals the size of the array minus one
		{                                                 //as long as the index is greater than p_index(insertion area)
			m_array[index] = m_array[index - 1];          //keep on copying the previous index to the current index
			m_array[p_index] = p_item;                    //once we reach the p_index(insertion area), we insert the 
		}                                                 // the value we passed in as p_item
	}

	void Remove(int p_index)                               //pass in the index you want to remove
	{
		int index;                                         //declares an interator
		for(index = p_index + 1;  index < m_size; index++) //the iterator index is located just one index above the area you want to remove
		{                                                  //as long as iterator index is less than the size of the array
			m_array[index-1] = m_array[index];             //keep on copying to the index right behing the intertor index
		}
	}

	int Size()  //function the retrives the array size
	{
		return m_size;
	}


//function that writes to the disk first
    bool WriteFile(const char p_filename[]) //pass in a file name
    {
	    FILE* outfile = 0; //pointer to a file opbject, currently set to NULL/0
	    int written = 0;    //keeps track of how many items were written
	    outfile = fopen(p_filename, "wb"); //the outfile pointer now points to the file you passed in, and opens it
	    if(outfile == 0) //checking to see if the file opened or not
	    {
		    return false; //if it isnt open, return false
	    }
	    written = fwrite (m_array, sizeof(datatype), m_size, outfile); //writing the data to the file,  pass in
	                                                             //(pointer to array, size of data, size of array, the destination file);
	
	    fclose(outfile); //close the file                            
	    if(written != m_size)//checking to see if the file was written or not
		{
		return false;  //if not, return flase
		}
	    return true; //if it did, return true;
	}

//function that reads the file from the disk
	bool ReadFile(const char p_filename[])
	{
		FILE* infile = 0;
		int read = 0;
		infile = fopen(p_filename, "rb");
		if(infile == 0)
		{
			return false;
		}
		read = fread(m_array, sieof(datatype), m_size, infile);
		fclose(infile);
		if(read != m_size)
		{
			return false;
		}
		return true;
	}


	
};

If nothing else, I'd make a guess that your PrintArray() function will crash when trying to dereference deleted memory because you did not follow the Rule of Three in your Array class.

Stephen M. Webb
Professional Free Software Developer

This topic is closed to new replies.

Advertisement