Riptyde4
Riptyde4

Reputation: 5460

qsort() on a 1-indexed array is messing up indexing

I'm using a 1-indexed array that I'm trying to sort by profit/price ratios. I have a comparison function written out, it all works, but it's placing the first element in index 0. I would just move the elements over, but the array is quite large and this would add a significant amount to the time complexity

Does anyone know of a sort that would be compatible with an array of this type? As in one where I can specify the beginning of the array?

I tried using the following

qsort(problemCards+sizeof(Card), problemBank[i].getNumCards(), sizeof(Card), compare);

but I get an arithmetic error on one of the calls to the compare function....

I'm really trying to avoid having to write my own sort for this so any help would be greatly appreciated, thanks!

Upvotes: 0

Views: 127

Answers (1)

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

Reputation: 275310

Here is how to call std::sort with your data:

bool card_less( const Card& lhs, const Char& rhs ) {
  return compare(&lhs, &rhs)<0;
}

Card* start = problemCards+1;
Card* end = start + problemBank[i].getNumCards();
std::sort( start, end, card_less );

This assumes that compare is a free function that takes two Card const*. We define card_less to be another free function that uses compare to tell you if the lhs is less than the rhs.

Upvotes: 2

Related Questions