# 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 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 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.

thx guys, :)

## Create an account

Register a new account

• ### Forum Statistics

• Total Topics
628366
• Total Posts
2982273

• 10
• 9
• 13
• 24
• 11