Skip to content

Commit 290fd91

Browse files
committed
implement quadratic probing, add comments
1 parent 2c2c277 commit 290fd91

1 file changed

Lines changed: 15 additions & 2 deletions

File tree

entries/ghatem-fpc/src/onebrc.pas

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,7 @@ function Compare(AList: TStringList; AIndex1, AIndex2: Integer): Integer;
131131

132132
procedure TMyDictionary.InternalFind(const aKey: Cardinal; out aFound: Boolean; out aIndex: Integer);
133133
var vIdx: Integer;
134+
vOffset: Integer;
134135
begin
135136
vIdx := aKey mod cDictSize;
136137
aFound := False;
@@ -140,16 +141,24 @@ procedure TMyDictionary.InternalFind(const aKey: Cardinal; out aFound: Boolean;
140141
aFound := True;
141142
end
142143
else begin
144+
vOffset := 1;
143145
while True do begin
144-
Inc (vIdx);
146+
// quadratic probing, by incrementing vOffset
147+
Inc (vIdx, vOffset);
148+
Inc (vOffset);
149+
150+
// exceeded boundary, loop back
145151
if vIdx >= cDictSize then
146152
Dec (vIdx, cDictSize);
153+
147154
if FHashes[vIdx] = aKey then begin
155+
// found match
148156
aIndex := vIdx;
149157
aFound := True;
150158
break;
151159
end
152160
else if FHashes[vIdx] = 0 then begin
161+
// found empty bucket to use
153162
aIndex := vIdx;
154163
aFound := False;
155164
break;
@@ -364,7 +373,10 @@ procedure TOneBRC.Merge(aLeft: UInt16; aRight: UInt16);
364373
vDataL: PStationData;
365374
begin
366375
for iHash in FStationsDicts[aRight].Keys do begin
367-
if iHash = 0 then continue;
376+
// zero means empty slot: skip
377+
if iHash = 0 then
378+
continue;
379+
368380
FStationsDicts[aRight].TryGetValue(iHash, vDataR);
369381

370382
if FStationsDicts[aLeft].TryGetValue(iHash, vDataL) then begin
@@ -407,6 +419,7 @@ procedure TOneBRC.GenerateOutput;
407419
try
408420
vStations.BeginUpdate;
409421
for vData in FStationsDicts[0].Values do begin
422+
// nil value means empty slot: skip
410423
if vData <> nil then
411424
vStations.Add(vData^.Name);
412425
end;

0 commit comments

Comments
 (0)