views:

287

answers:

3

So the idea is to sort a large STRUCTURE using an element of that structure, for arguments sake Zip Code.

To keep it simple lets pretend that there are two arrays, one integer containing the zip codes and two, a larger structure (3k Bytes) array.

Sorting the integer array is suitably fast with Quick Sort, but tagging the Structure array could be done a little better than simply swapping elements when the integer array swaps elements.

In testing a random 3000 element integer array required 12000 swaps to achieve a completed sort. Swapping the entire structure that many times would have a performance penalty esp if there are many elements.

Ideally I would just sort an array of pointers, but in this case I actually have to return a sorted structure array not an array of sorted pointers. If nothing else this is an exercise in sorting a tagged array.

One approach would be to tag a secondary integer array, and then use the order within it to shuffle the elements of the structure around, thus moving each element only once.

I am not finding much help on the web http://rosettacode.org/wiki/Sorting_an_Array_of_Integers#C

Suggestions for an elegant design would be appreciated.

A: 

In the above you should really be using std::vectors, not arrays. I can't imagine why you can't return a (const) vector of pointers, but if that is the case, work with a vector of pointers, sorting only the pointers and then when sorted, copy the resulting sorted structures into another vector and return that, which will mean only one copy per vector entry.

anon
Thank you. Yes I could copy the elements into another array, but I wanted to try an do it in place. The array can be subject to a filtering operation in which it's size is reduced in complex ways. This could be done by gathering the elements from the array of pointers, but I am told the code re-write would be substantial. I am tasked with doing the best I can within the constraints.
Mike Trader
I can't see how you can possibly do it in place without exchanging the actual structure data.
anon
Well, the idea would be to produce an integer array that maps the old positions to the new positions. Then if you store the first element in a buffer, you could move the element that replaces it into its slot an then the element that replaces that element and so forth, finally putting the buffered element in its location.
Mike Trader
+1  A: 

If you want to avoid swapping overhead, you could try Selection Sort. This sorting algorithm will find a value and immediatly put it into the right place performing only one swap, thus, I believe, doing the minimal number of swaps as possible.

fjsj
A: 

You could put it into a std::list and then define the comparison function for the sort. It should only swap the pointers to each node and not the structures. Swaping of pointers is a quick 2 or 3 op function.

Beached