How to sort an array of integers with zeros at the end?

I need to sort arrays by an integer field, with 1-n sorted at the beginning and zeros last: 0,0,3,1,2 → 1,2,3,0,0

I do not know how to sort it at a time, so I tried in 2 sorts, but it does not give the correct results:

He put zeros at the end, but he messed up the 1st ordered element:

0,0,3,1,2 → (first grade) 0,0,1,2,3 → (second grade) 2,3,1,0,0

procedure TForm2.Button1Click(Sender: TObject); var Arr: TArray<integer>; begin SetLength(Arr, 5); Arr[0] := 0; Arr[1] := 0; Arr[2] := 3; Arr[3] := 1; Arr[4] := 2; // First sort: Sort 1-n TArray.Sort<integer>(Arr, TComparer<integer>.Construct(function(const Left, Right: integer): Integer begin if Left < Right then Result := -1 else if Left > Right then Result := 1 else Result := 0; end )); // Second sort: Put zeros at the end TArray.Sort<integer>(Arr, TComparer<integer>.Construct(function(const Left, Right: integer): Integer begin if (Left = 0) and (right>0) then Result := 1 else Result := 0; end )); end; 

Is there a way to do this sort in one, one sort operation?

+5
source share
2 answers

Try this, dealing with special 0 cases first on the if-then-else ladder, before ordinary cases.

  TArray.Sort<integer>(Arr, TComparer<integer>.Construct(function(const Left, Right: integer): Integer begin if (Left = 0) and (Right = 0) then Result := 0 else if (Left = 0) then Result := 1 else if (Right = 0) then Result := -1 else if (Left < Right) then Result := -1 else if (Left > Right) then Result := 1 else Result := 0; end )); 

A quick test shows that it is working fine.

+9
source

Just fix the comparison function so that it treats the value 0 as something more.

Unverified:

 TArray.Sort<integer>(Arr, TComparer<integer>.Construct(function(const Left, Right: integer): Integer begin if Left = Right then Result := 0 else if ((Left <> 0) and (Left < Right)) or (Right = 0) then Result := -1 else Result := 1; end )); 
+4
source

Source: https://habr.com/ru/post/1274544/


All Articles