Reputation: 111
I am using the C library function qsort to sort a bunch of integer keys. Any ideas, suggestions, pointers on how I can extend it to sort key-value pairs, where the integer keys can have any associated value? Thanks!
Upvotes: 1
Views: 1376
Reputation: 1
//just quick sorting function (with key-index array to maintain identity)
//inefficient but works
void quicksort(int *values, int *keys, int count)
{
bool bool_sorted = false;
int temp;
//check whether all keys are in the correct order
while (bool_sorted == false)
{
bool_sorted = true;
for (int i = 0; i < count-1; i++)
{
//if next value is lower
if (values[i] > values[i+1])
{
//swap + key index
temp = values[i];
values[i] = values[i+1];
values[i+1] = temp;
temp = keys[i];
keys[i] = keys[i+1];
keys[i+1] = temp;
bool_sorted = false;
}
}
}
}
Posted for convenience of anyone else looking for an actual answer.
Upvotes: 0
Reputation: 15526
Use an array of (fixed sized) structs, and supply your own comparison functions.
Upvotes: 4
Reputation: 143229
Use struct { int key; void *value; }
and a function that does the comparison?
Upvotes: 1