Sort isues with TArray for large numbers


Sort isues with TArray<Myrectype> for large numbers



What is the reason why TArray.Sort does not work when I have large numbers in the comparison ?



My code is as follows (Delphiy Tokyo):


Interface

Type
RCInd = record
Num : Integer;
Ger : Integer;
Confirmed : Boolean;
Total : Real;
End;

TArrInd = TArray<RCInd>;

Procedure SortInd (Var PArrayInd : TArrInd);

Implementation

Procedure SortInd (Var PArrayInd : TArrInd);
begin
TArray.Sort<RCInd>( PArrayInd,TComparer<RCInd>.Construct
( function (Const Rec1, Rec2 : RCInd) : Integer
begin
Result := - ( Trunc(Rec1.Total) - Trunc(Rec2.Total) );
end )
);
end;

......



When the values of Rec1.Total and Rec2.Total are whithin a Integer limits , this Sort works fine , BUT when values exceed Integer limits Sort procedure does not work ! It generates a non sorted set of data in PArrayInd .



Does anyone help me to understand what is going on here ?
Thks in advance !




1 Answer
1



The problem is one of overflow. The real values overflow the integer type.



The compare function is meant to return negative to indicate less than, positive to. Indicate greater than and zero to indicate equal. Your using arithmetic is the cause of your problem, leading as it does to overflow. Instead use comparison operators.


function(const Rec1, Rec2: RCInd): Integer
begin
if Rec1.Total < Rec2.Total then
Result := 1
else if Rec1.Total > Rec2.Total then
Result := -1
else
Result := 0;
end;



The problem in this question is trying to fit a real value into an integer, but even if you have integer data then arithmetic should not be used for compare functions. Consider the expression


Low(Integer) - 1



This results in overflow. As a general principle, always use comparison operators to implement compare functions.





that is it ! I changed the function as you proposed and it worked ! Thanks a lot !
– JRG
Jun 30 at 5:45






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Extract Id from Twitch Clip URL

Why are these constructs (using ++) undefined behavior in C?

I'm Still Waiting (Diana Ross song)