2

I want to know which search algorithm does lsearch in tcl uses in the background. Also, if the list is sorted and we have not given the option -sorted in the lsearch, does it still uses binary search to perform the search. And if there is any way to make lsearch more efficient, Do let me know.

I tried different cases and i am still confused as which way is the most efficient.

  • 3
    Tcl doesn't (currently) keep the information that the list is sorted in an efficient-to-access form (i.e., some sort of flag bit), so it would have to do a linear scan as it doesn't know that it can do anything more efficient. That would be an enhancement that could be added… but we don't do so right now and there isn't really a pressing need. The programmer can specify `-sorted` quite easily! – Donal Fellows Mar 31 '22 at 10:59

1 Answers1

5

If you don't specify -sorted it will do a linear scan, note that you can change the starting point for this with the -start option, see https://www.tcl-lang.org/man/tcl/TclCmd/lsearch.htm#M14 , also using -sorted implies exact matching, not glob or regexp.

If you need to search for a value in a large set it's likely to be more efficient to use a Tcl array or a dict since these use hashing to find exact matches quickly.

Colin Macleod
  • 4,222
  • 18
  • 21
  • What if the list is unsorted and still we give -sorted option in lsearch. Will there be a chance that item will not be found even if it is in the list since search should be binary search in case we give -sorted option. – Dipender Siwach Apr 01 '22 at 07:52
  • 1
    I think you would be into **undefined behaviour** territory there – Colin Macleod Apr 01 '22 at 08:43