I have such a struct
struct OfferBid {
string id_user;
uint qty_energy;
uint typ;
uint price_energy;
uint status;
uint t_submission;
uint ts_delivery;
uint number;
uint quality_energy;
}
and I have an array of this struct:
OfferBid[] tempOffers;
I found out how to sort tempOffers
by price_energy
. I use this function which creates an array of unit from the field price
:
function quickSortOffersBidsPrice(Lb.Lib.OfferBid[] memory arr, bool ascending) public view returns(Lb.Lib.OfferBid[] memory) {
if(arr.length == 0) return arr;
uint[] memory prices = lib.arr_of_prices_offerbids(arr);
Lb.Lib.OfferBid[] memory sorted = get_indices_and_sort(prices,arr,ascending);
return sorted;
}
which calls these other functions: Here I create an array of unit with the indices of the array of struct.
function get_indices_and_sort(uint[] memory values, Lb.Lib.OfferBid[] memory offers_bids, bool ascending) private pure returns(Lb.Lib.OfferBid[] memory) {
uint[] memory indices = new uint[](values.length);
for (uint z = 0; z < indices.length; z++) {
indices[z] = z;
}
Sorting.quickSort_indices(values, 0, int(values.length-1), indices);
if(!ascending){
indices = reverseArray(indices);
}
Lb.Lib.OfferBid[] memory sorted = new Lb.Lib.OfferBid[](values.length);
for (uint z = 0; z < indices.length; z++) {
sorted[z] = offers_bids[indices[z]];
}
return sorted;
}
I sort the array of prices and then at the same time the indices. Then I can sort the original array of struct
function quickSort_indices(uint[] memory arr, int left, int right, uint[] memory indices) public pure {
int i = left;
int j = right;
if (i == j) return;
uint pivot = arr[uint(left + (right - left) / 2)];
while (i <= j) {
while (arr[uint(i)] < pivot) i++;
while (pivot < arr[uint(j)]) j--;
if (i <= j) {
(arr[uint(i)], arr[uint(j)]) = (arr[uint(j)], arr[uint(i)]);
(indices[uint(i)], indices[uint(j)]) = (indices[uint(j)], indices[uint(i)]);
i++;
j--;
}
}
if (left < j)
quickSort_indices(arr, left, j, indices);
if (i < right)
quickSort_indices(arr, i, right, indices);
}
How can I sort it first by price_energy
, and in case of same price_energy
, sort it byqty_energy
?