program TArrayTest; {$APPTYPE CONSOLE} uses SysUtils, Generics.Collections, Generics.Defaults, Windows; var arr: array of string; i, findIndex: integer; count: Cardinal; begin setLength(arr, 5); count := Gettickcount; for i := 0 to 4 do begin arr[i] := IntToStr(5 - i) + '个数'; end; TArray.Sort<string>(arr, Generics.Defaults.TStringComparer.Ordinal); //依序排序 for i := 0 to 4 do writeln(arr[i]); try // 数组 搜索对象 保存的结果 if TArray.BinarySearch<string>(arr, '3个数', findIndex, Generics.Defaults.TStringComparer.Ordinal, 0, 4) then //最后是开始和结束的索引 成功返回true,否则false begin writeln('Element:3个数 is found -- ', findIndex); end else begin writeln('not found'); end; except writeln('exception'); end; writeln(Gettickcount - count); // 计算运行的时间 readln; end.
class procedure TArray.Sort<T>(var Values: array of T); begin QuickSort<T>(Values, TComparer<T>.Default, Low(Values), High(Values)); end;
class procedure TArray.QuickSort<T>(var Values: array of T; const Comparer: IComparer<T>; L, R: Integer); var I, J: Integer; pivot, temp: T; begin if (Length(Values) = 0) or ((R - L) <= 0) then Exit; repeat I := L; J := R; pivot := Values[L + (R - L) shr 1]; repeat while Comparer.Compare(Values[I], pivot) < 0 do Inc(I); while Comparer.Compare(Values[J], pivot) > 0 do Dec(J); if I <= J then begin if I <> J then begin temp := Values[I]; Values[I] := Values[J]; Values[J] := temp; end; Inc(I); Dec(J); end; until I > J; if L < J then QuickSort<T>(Values, Comparer, L, J); L := I; until I >= R; end;
二分查找算法:
class function TArray.BinarySearch<T>(const Values: array of T; const Item: T; out FoundIndex: Integer; const Comparer: IComparer<T>; Index, Count: Integer): Boolean; var L, H: Integer; mid, cmp: Integer; begin if (Index < Low(Values)) or ((Index > High(Values)) and (Count > 0)) or (Index + Count - 1 > High(Values)) or (Count < 0) or (Index + Count < 0) then raise EArgumentOutOfRangeException.CreateRes(@SArgumentOutOfRange); if Count = 0 then begin FoundIndex := Index; Exit(False); end; Result := False; L := Index; H := Index + Count - 1; while L <= H do begin mid := L + (H - L) shr 1; cmp := Comparer.Compare(Values[mid], Item); if cmp < 0 then L := mid + 1 else begin H := mid - 1; if cmp = 0 then Result := True; end; end; FoundIndex := L; end;