Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort an array by an index array in C [duplicate]

Tags:

c

algorithm

Possible Duplicate:
In-place array reordering?

I have original unsorted array with structures such as:

{D, A, B, E, C}

and array of indexes of original array in sorted order:

{2, 3, 5, 1, 4} // Edited. Then I get {A, B, C, D, E}.

How can I simply rearranged the originial array by an index array?

I can't create new array and insert elements by index-position.

like image 919
Peter K. Avatar asked Nov 22 '25 01:11

Peter K.


1 Answers

My 5 cents:

int new_i;
for (int i = 0; i < arr_size-1; ++i)
{
    while ((new_i = index_arr[i]-1) != i)
    {
        std::swap(struct_arr[i], struct_arr[new_i]);
        std::swap(index_arr[i], index_arr[new_i]);
    }
}
like image 122
panda-34 Avatar answered Nov 23 '25 16:11

panda-34



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!