![]() |
Blitz Support : |
From: Jonathan Stickel (jjstickel_at_[hidden])
Date: 2003-08-05 12:53:30
Thanks for suggestions! I was able to implement a sorting function by
using a vector of pairs. It turns out that boolean operators on pairs
operate on the first element, so I didn't need to define a class to do
the sorting. I have attached the code below. It can sort the rows of
any m x n Blitz array by the specified column. It would be trivial to
modify the function to sort columns by specified row number.
I wonder if there might be interest in making this a member function of
the Array class?
Regards,
Jonathan
/*Sort the rows of a 2D array by a single column (colNumb). The column
to be sorted is copied to vector of pairs where the first pair
element is the value and the second is the row index number. This
pair vector is sorted by the values, and the the ordered indexes are
used to reorder the table accordingly.
Could also write functions to sort the columns (and even pages of 3D
arrays).
*/
template <class Type>
void sortRows(Array<Type,2> & table, const int colNumb)
{
int i, j, m=table.rows(), n=table.columns();
vector< pair<Type,int> > valIndPair(m);
for (i=0; i<m; ++i) {
valIndPair[i].first = table(i,colNumb);
valIndPair[i].second=i;
}
sort(valIndPair.begin(), valIndPair.end());
Array<Type,1> colReord(m);
for (j=0; j<n; ++j) {
if (j==colNumb)
for (i=0; i<m; ++i)
table(i,j)=valIndPair[i].first;
else {
colReord=table(rAll,j);
for (i=0; i<m; ++i)
table(i,j) = colReord(valIndPair[i].second);
}
}
}