Applying a binary search to a table of an atom

All topics on coding 4Dscript in Enterprise Dynamics.
Post Reply
Assil
Posts: 3
Joined: Tuesday 19 April, 2011 - 14:09

Applying a binary search to a table of an atom

Post by Assil »

Say I have an atom containing a table with a lot of values in it. Can I apply a Binary Search algorithm to find the row containing that value?

Well, to apply any search algorithm, first make sure that the table is appropriately sorted, that is, the column that needs to be searched, has to be sorted.
ED does not have a builtin, off the shelf, functionality that applyes the binary search but you can easily make your own method. Here is the code:

BinarySearch(e1, e2, e3)
where
e1: Atom containing the table
e2: Column number where the value should be searched
e3: The value that should be searched for

Code: Select all

Do(
 var([atmTable], vbAtom, p(1)),
 var([valColumn], vbValue, p(2)),
 var([valValueToSearchFor], vbValue, p(3)),
 var([valLowerBoundary], vbValue),
 var([valUpperBoundary], vbValue),
 var([valMiddlePoint], vbValue),
 var([valFound], vbValue),
 
 valFound := False,
 valLowerBoundary := 0,
 valUpperBoundary := nRows(atmTable),
 
 if(
  Cell(valUpperBoundary, valColumn, atmTable) = valValueToSearchFor,
  Do(
   valMiddlePoint := valUpperBoundary,
   valFound := True
  )
 ),
 
 LoopUntil(
  Or(
   valFound,
   valLowerBoundary + 1 >= valUpperBoundary
  ),
  Do(
   valMiddlePoint := Trunc((valLowerBoundary + valUpperBoundary )/2),
   if(
    Cell(valMiddlePoint, valColumn, atmTable) = valValueToSearchFor,
    valFound := True,
    if(
     Cell(valMiddlePoint, valColumn, atmTable) < valValueToSearchFor,
     valLowerBoundary := valMiddlePoint,
     valUpperBoundary := valMiddlePoint
    )
   )
  )
 ),
 if(
  valFound,
  valMiddlePoint,
  0
 )
)
MarvinH
Posts: 93
Joined: Tuesday 25 January, 2011 - 11:07
Contact:

Re: Applying a binary search to a table of an atom

Post by MarvinH »

Does this code take the headers of the table into account?
Post Reply