Sign in to follow this  
Tutukun

need help with sorting algorithm :(

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[i]->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
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[i], but nodeList[i] 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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this