Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if Array is sorted?

How can I check if TArray is already sorted? I am using the default TArray.Sort to sort my array.

like image 952
user3764855 Avatar asked Mar 21 '26 18:03

user3764855


1 Answers

Check neighbour pairs with the same comparator as Sort uses

Result := True;
for i := Low(Arr) + 1 to High(Arr) do
  if Compare(Arr[i], Arr[i - 1]) < 0 then
    Exit(False);

It takes O(n) time (against O(nlogn) for sorting)

like image 91
MBo Avatar answered Mar 24 '26 01:03

MBo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!