• Advertisement
Sign in to follow this  

need help with sorting algorithm :(

This topic is 4476 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi guys I have a class like this class Node{ ..... int h; ... }; then a vector contain pointer to Node: vector<Node*> nodeList; Now im trying to compare h from each pointer from nodeList then sort all the pointers in the ascending order (due to h) I tried to do this If(nodeList->GetH() > nodeList[i+1]->GetH()) { //swap element i to i+1 } but eventually it will give me an out of bound error :(. So what should I do Thx in advance }

Share this post


Link to post
Share on other sites
Advertisement
Question: Is all you care about is getting this sorted, or are you trying to learn the basics of sorting?

If the former, write a function that compares your structures, and use std::sort.

If the latter, you appear to be performing bubble sort, this is rarely a good choice. There are a few articles on Gamedev that discuss alternatives. But your specific problem is probably an off by one error. Your array only has N elements, and you are likely looping something like for(int i = 0; i < N; i++). This causes your last iteration to compare nodeList[i-1] to nodeList, but nodeList is not a valid element. Dwell on that a bit, and a solution should come to you.

CM

Share this post


Link to post
Share on other sites

#include <algorithm>
#include <vector>

using namespace std;

struct node
{
node( int n ) : h(n) {};
int h;
}


bool compare_node_ptr( const node* const left, const node* const right )
{
return (left->h < right->h);
}

int main()
{
vector<node*> nodelist;
node n1( 5 ), n2( 1 ), n3( 3 );

nodelist.push_back( &n1 );
nodelist.push_back( &n2 );
nodelist.push_back( &n3 );

sort( nodelist.begin(), nodelist.end(), compare_node_ptr );

return 0;
}





edit: Awww. Beaten to it.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement