3

I have an array stored in memory. How to sort it according to a column?

 2 years ago
source link: https://www.codesd.com/item/i-have-an-array-stored-in-memory-how-to-sort-it-according-to-a-column.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

I have an array stored in memory. How to sort it according to a column?

advertisements

I have a table stored in contiguous memory. It needs to stay in that format after the sort.

For example:

int table[5][3] = {
    { 60, 5, 10 },
    { 0, 200, 15 },
    { 55, 50, 365 },
    { 4, 7, 78 },
    { 555, 8, 11 },
};

Except much bigger (the size of the biggest, in bytes, is approximately 27 KB). Each cell is always an int32, and all rows have the same amounts of columns.

Let's say that I want to sort it based on the first column, so that the result must be equivalent to:

    { 0, 200, 15 },
    { 4, 7, 78 },
    { 55, 50, 365 },
    { 60, 5, 10 },
    { 555, 8, 11 },

What's the best way to do this? I imagine there is a better way than to convert this to a std::list, call sort(), and convert back.

Also, something built into C++ where I just have to call some function would be best.


std::sort won't do it easily because arrays aren't assignable.

However, std::qsort will do it:

int cmp_first_column(const void *lhs_, const void *rhs_) {
    // optimize this to taste
    const int *lhs = static_cast<const int*>(lhs_);
    const int *rhs = static_cast<const int*>(rhs_);
    if (lhs[0] < rhs[0]) return -1;
    if (lhs[0] > rhs[0]) return 1;
    return 0;
}

std::qsort(table, 5, 3*sizeof(int), cmp_first_colum);

OK, so std::qsort doesn't benefit from template inlining optimization, but it gets the job done and at least you aren't allocating a lot of memory and doing unnecessary copying.

You could instead look to replace your array of int[3] with an array of structs with an int[3] as a data member. That would then be assignable and you could use std::sort normally. Depends how much other code you have written that relies on the current type, and whether it's OK to break the interface that code uses.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK