Jump to content
Tom F

Generic sort of several "parallel" arrays?

Recommended Posts

In a plotting app, I have the following class of: x ,y points, a string label for each point, and an array of Booleans indicating whether the point should be plotted. All 4 arrays will be of the same length.

  TXYSeries = class(TObject)
                 fXSeries: array of Single;
                 fYSeries: array of Single;;
                 fIgnorePointWhenPlotting: array of Boolean;
                 fElementNames: array of String;
              end;

 

I want to sort the arrays in this object so that  the values in fXSeries are in order.

Any suggestions on a clever way to do this sort using generics or other built-in sort methods? (i.e. I really don't want to use my own sort code.)


The only approach I can come up with is to copy the above class into an array of point objects. Do a generic sort of the array. Then copy the array back into the structure in the above code sample.

This seems pretty clumsy. But maybe the original data structure above doesn't lend itself to generics?  Any suggestions.

 

Below is my proposed solution:

 

type
  TPoint = class(TObject)
    X: Single;
    Y: Single;
    Ignore: Boolean;
    ElementName: String;
  end;

  TPoints = Array of TPoint;

  var Points: TPoints;
begin
  ... TXYObject into Points array...
  
  TArray.Sort<TPoint>( Points, ....)
  
  ... Copy Points array into TXYObject
  
end;

 

 

Edited by Tom F

Share this post


Link to post

Is this telling you is that your data structure is wrong? What you need is a record with the 4 values and then array of that record. Then basic array sort with custom comparer gets it done. 

 

Then again, perhaps you so need direct access to contiguous arrays of each of the 4 scalars. 

 

As stated you really need a sort algo that allows you to provide both comparer and exchanger. I had such a thing once. 

 

The final approach is not to modify the arrays at all. Create an integer array with values from 0 to N-1 and then sort that using the x values to determine the order. Have the compare function return 

 

CompareSingle(x[idx[left], x[idx[right]])

 

Edited by David Heffernan
  • Like 1

Share this post


Link to post

Unless there's some specific requirements, the most logical solution is to extract all point properties to separate structure and sort them as you like. You can also have arrays of pointers to these structures each one sorted by different fields.

Edited by Fr0sT.Brutal

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×