FANDOM


16px-Pencil

A searching algorithm is an algorithm that aims to find an item within a collection of items.

There are many kinds of searching algorithms, including:

  • list search algorithms, which search for an item in a linear (one-dimensional) collection, for example, an array.
    • linear search, searches any list, runs in O(n). Typically a search like this would use a loop to iterate through the list until the required item was found.
    • binary search, searches a sorted list, runs in O(log n).
  • tree searching algorithms, which search for an item in a tree.
  • string searching algorithms, which search for patterns within strings

Bash Edit

function in_array {
   for i in "${@:2}"; do
      [[ "$i" == "$1" ]] && return 0
   done
} 

haystack=("apple" "orange" "yellow banana")
in_array "orange" "${haystack[@]}" && echo found || echo not found

Go Edit

func in_array(needle interface{}, haystack []interface{}) (exists bool) {
   for i := range haystack {
      if exists = haystack[i] == needle; exists {
         return
      }
   }
   return
}

Java Edit

Java implements the binary search in both the Collections and Arrays classes.

JavaScript Edit

From all modern browsers and IE9+ you can use Array.prototype.indexOf():

var present = haystack.indexOf(needle) > -1;

You can either polyfill the standard function with the above mentioned MDN article on indexOf() or use a simpler version:

function in_array(needle,haystack) {
	if(!haystack instanceof Array) throw 'Error: Haystack isn\'t an array.';
	for(var i in haystack) if(haystack[i]==needle) return true;
	return false;
}

Or if you use jQuery anyways:

var present = $.inArray(needle, haystack) > -1;

Perl Edit

if(grep $_ eq $needle, @haystack) {
	print "Success!";
}

See Also Edit

Ad blocker interference detected!


Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.