Как найти элементы массива с определенным значением

(PHP 4 >= 4.0.5, PHP 5, PHP 7, PHP 8)

array_searchSearches the array for a given value and returns the first corresponding key if successful

Description

array_search(mixed $needle, array $haystack, bool $strict = false): int|string|false

Parameters

needle

The searched value.

Note:

If needle is a string, the comparison is done
in a case-sensitive manner.

haystack

The array.

strict

If the third parameter strict is set to true
then the array_search() function will search for
identical elements in the
haystack. This means it will also perform a
strict type comparison of the
needle in the haystack,
and objects must be the same instance.

Return Values

Returns the key for needle if it is found in the
array, false otherwise.

If needle is found in haystack
more than once, the first matching key is returned. To return the keys for
all matching values, use array_keys() with the optional
search_value parameter instead.

Warning

This function may
return Boolean false, but may also return a non-Boolean value which
evaluates to false. Please read the section on Booleans for more
information. Use the ===
operator for testing the return value of this
function.

Examples

Example #1 array_search() example


<?php
$array
= array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array); // $key = 1;
?>

See Also

  • array_keys() — Return all the keys or a subset of the keys of an array
  • array_values() — Return all the values of an array
  • array_key_exists() — Checks if the given key or index exists in the array
  • in_array() — Checks if a value exists in an array

turabgarip at gmail dot com

6 years ago


About searcing in multi-dimentional arrays; two notes on "xfoxawy at gmail dot com";

It perfectly searches through multi-dimentional arrays combined with array_column() (min php 5.5.0) but it may not return the values you'd expect.

<?php array_search($needle, array_column($array, 'key')); ?>

Since array_column() will produce a resulting array; it won't preserve your multi-dimentional array's keys. So if you check against your keys, it will fail.

For example;

<?php
$people
= array(
 
2 => array(
   
'name' => 'John',
   
'fav_color' => 'green'
 
),
 
5=> array(
   
'name' => 'Samuel',
   
'fav_color' => 'blue'
 
)
);
$found_key = array_search('blue', array_column($people, 'fav_color'));
?>

Here, you could expect that the $found_key would be "5" but it's NOT. It will be 1. Since it's the second element of the produced array by the array_column() function.

Secondly, if your array is big, I would recommend you to first assign a new variable so that it wouldn't call array_column() for each element it searches. For a better performance, you could do;

<?php
$colors
= array_column($people, 'fav_color');
$found_key = array_search('blue', $colors);
?>


cue at openxbox dot com

19 years ago


If you are using the result of array_search in a condition statement, make sure you use the === operator instead of == to test whether or not it found a match.  Otherwise, searching through an array with numeric indicies will result in index 0 always getting evaluated as false/null.  This nuance cost me a lot of time and sanity, so I hope this helps someone.  In case you don't know what I'm talking about, here's an example:

<?php

$code
= array("a", "b", "a", "c", "a", "b", "b"); // infamous abacabb mortal kombat code :-P

// this is WRONG

while (($key = array_search("a", $code)) != NULL)

{

// infinite loop, regardless of the unset

unset($code[$key]);

}
// this is _RIGHT_

while (($key = array_search("a", $code)) !== NULL)

{

// loop will terminate

unset($code[$key]);

}

?>


stefano@takys dot it

12 years ago


for searching case insensitive better this:

<?php

array_search
(strtolower($element),array_map('strtolower',$array));

?>


RichGC

17 years ago


To expand on previous comments, here are some examples of
where using array_search within an IF statement can go
wrong when you want to use the array key thats returned.

Take the following two arrays you wish to search:

<?php
$fruit_array
= array("apple", "pear", "orange");
$fruit_array = array("a" => "apple", "b" => "pear", "c" => "orange");

if (

$i = array_search("apple", $fruit_array))
//PROBLEM: the first array returns a key of 0 and IF treats it as FALSEif (is_numeric($i = array_search("apple", $fruit_array)))
//PROBLEM: works on numeric keys of the first array but fails on the secondif ($i = is_numeric(array_search("apple", $fruit_array)))
//PROBLEM: using the above in the wrong order causes $i to always equal 1if ($i = array_search("apple", $fruit_array) !== FALSE)
//PROBLEM: explicit with no extra brackets causes $i to always equal 1if (($i = array_search("apple", $fruit_array)) !== FALSE)
//YES: works on both arrays returning their keys
?>


thinbegin at gmail dot com

5 years ago


Despite PHP's amazing assortment of array functions and juggling maneuvers, I found myself needing a way to get the FULL array key mapping to a specific value. This function does that, and returns an array of the appropriate keys to get to said (first) value occurrence.

function array_recursive_search_key_map($needle, $haystack) {
    foreach($haystack as $first_level_key=>$value) {
        if ($needle === $value) {
            return array($first_level_key);
        } elseif (is_array($value)) {
            $callback = array_recursive_search_key_map($needle, $value);
            if ($callback) {
                return array_merge(array($first_level_key), $callback);
            }
        }
    }
    return false;
}

usage example:
-------------------

$nested_array = $sample_array = array(
    'a' => array(
        'one' => array ('aaa' => 'apple', 'bbb' => 'berry', 'ccc' => 'cantalope'),
        'two' => array ('ddd' => 'dog', 'eee' => 'elephant', 'fff' => 'fox')
    ),
    'b' => array(
        'three' => array ('ggg' => 'glad', 'hhh' => 'happy', 'iii' => 'insane'),
        'four' => array ('jjj' => 'jim', 'kkk' => 'kim', 'lll' => 'liam')
    ),
    'c' => array(
        'five' => array ('mmm' => 'mow', 'nnn' => 'no', 'ooo' => 'ohh'),
        'six' => array ('ppp' => 'pidgeon', 'qqq' => 'quail', 'rrr' => 'rooster')
    )
);

$search_value = 'insane';

$array_keymap = array_recursive_search_key_map($search_value, $nested_array);

var_dump($array_keymap);
// Outputs:
// array(3) {
// [0]=>
//  string(1) "b"
//  [1]=>
//  string(5) "three"
//  [2]=>
//  string(3) "iii"
//}

----------------------------------------------

But again, with the above solution, PHP again falls short on how to dynamically access a specific element's value within the nested array. For that, I wrote a 2nd function to pull the value that was mapped above.

function array_get_nested_value($keymap, $array)
{
    $nest_depth = sizeof($keymap);
    $value = $array;
    for ($i = 0; $i < $nest_depth; $i++) {
        $value = $value[$keymap[$i]];
    }

    return $value;
}

usage example:
-------------------
echo array_get_nested_value($array_keymap, $nested_array);   // insane


opencart dot ocfilter at gmail dot com

1 year ago


Be careful!

<?php

var_dump

(array_search('needle', [ 0 => 0 ])); // int(0) (!)var_dump(array_search('needle', [ 0 => 0 ], true)); // bool(false)?>

But, in php 8

<?php

var_dump

(array_search('needle', [ 0 => 0 ])); // bool(false)?>


maciej at speccode dot com

7 years ago


FYI, remember that strict mode is something that might save you hours.

If you're searching for a string and you have a "true" boolean on the way - you will get it as result (first occurrence). Example below:

<?php

$arr

= [
   
'foo'    => 'bar',
   
'abc'    => 'def',
   
'bool'   => true,
   
'target' => 'xyz'
];var_dump( array_search( 'xyz', $arr ) ); //bool
var_dump( array_search( 'xyz', $arr, true ) ); //target?>


azaozz, gmail

14 years ago


Expanding on the comment by hansen{}cointel.de:

When searching for a string and the array contains 0 (zero), the string is casted to (int) by the type-casting which is always 0 (perhaps the opposite is the proper behaviour, the array value 0 should have been casted to string). That produces unexpected results if strict comparison is not used:

<?php
$a
= array(0, "str1", "str2", "str3");
echo
"
str1 = "
.array_search("str1", $a).",
str2 = "
.array_search("str2", $a).",
str3 = "
.array_search("str3", $a).",

str1 strict = "

.array_search("str1", $a, true).",
str2 strict = "
.array_search("str2", $a, true).",
str3 strict = "
.array_search("str3", $a, true);
?>

This will return:
str1 = 0, str2 = 0, str3 = 0, str1 strict = 1, str2 strict = 2, str3 strict = 3


codeslinger at compsalot dot com

13 years ago


one thing to be very aware of is that array_search() will fail if the needle is a string and the array itself contains values that are mixture of numbers and strings.  (or even a string that looks like a number)

The problem is that unless you specify "strict" the match is done using ==    and in that case any string will match a numeric value of zero which is not what you want.

-----

also, php can lookup an index pretty darn fast.  for many scenarios, it is practical to maintain multiple arrays, one in which the index of the array is the search key and the normal array that contains the data.

<?php

  $normal

[$index] = array('key'=>$key, 'data'=>'foo');

 
$inverse[$key] = $index;
//very fast lookup, this beats any other kind of search
if (array_key_exists($key, $inverse))

  {

   
$index = $inverse[$key];

    return
$normal[$index];

  }
?>


n-regen

14 years ago


If you only know a part of a value in an array and want to know the complete value, you can use the following function:
<?php
function array_find($needle, $haystack)
{
   foreach (
$haystack as $item)
   {
      if (
strpos($item, $needle) !== FALSE)
      {
         return
$item;
         break;
      }
   }
}
?>
The function returns the complete first value of $haystack that contains $needle.

andreas dot damm at maxmachine dot de

15 years ago


Combining syntax of array_search() and functionality of array_keys() to get all key=>value associations of an array with the given search-value:
<?php
function array_search_values( $m_needle, $a_haystack, $b_strict = false){
    return
array_intersect_key( $a_haystack, array_flip( array_keys( $a_haystack, $m_needle, $b_strict)));
}
?>

Usage:
<?php
$array1
= array( 'pre'=>'2', 1, 2, 3, '1', '2', '3', 'post'=>2);
print_r( array_search_values( '2', $array1));
print_r( array_search_values( '2', $array1, true));
print_r( array_search_values( 2, $array1, true));
?>

Will return:
array(4) {
    ["pre"] =>
    string(1) "2"
    [1] =>
    int(2)
    [4] =>
    string(1) "2"
    ["post"] =>
    int(2)
}
array(2) {
    ["pre"] =>
    string(1) "2"
    [4] =>
    string(1) "2"
}
array(2) {
    [1] =>
    int(2)
    ["post"] =>
    int(2)
}

yasien dot dwieb at gmail dot com

3 years ago


Beware when using array_search to a mix of string and integer where prefixes of keys may collide, as in my case I have encountered the following situation:

Assume you have the following array:
<?php
$arr
= [
          
1 => 'index 0',
          
2 => 'index 1',
          
3 => 'index 2',
          
'3anothersuffix' => 'index 3'
];$index1 = array_search('3', array_keys($arr)); // 2
$index2 = array_search('3anothersuffix', array_keys($arr)); //2
?>

$index1 and $index2 will be the same

after using strict type search:

<?php
$index1
= array_search('3', array_keys($arr), true); // false
$index2 = array_search('3anothersuffix', array_keys($arr), true);  //3
?>

it will not find $index1 at all while returning a correct value for $index2;


stooshie at gmail dot com

11 years ago


Example of a recursive binary search that returns the index rather than boolean.
<?php
// returns the index of needle in haystack
function binSearch($needle, $haystack)
{
   
// n is only needed if counting depth of search
   
global $n;
   
$n++;
   
// get the length of passed array
   
$l = count($haystack);
   
// if length is 0, problem
   
if($l <= 0)
    {
        return -
1;
    }
   
// get the mid element
   
$m = (($l+($l%2))/2);
   
// if mid >= length (e.g. l=1)
   
if($m >= $l)
    {
       
$m = $m-1;
    }
   
// get the indexed element to compare to the passed element and branch accordingly
   
$compare = $haystack[$m];
    switch(
true)
    {
        case(
$compare>$needle):
        {
           
// recurse on the lower half
           
$new_haystack = array_slice($haystack, 0, $m);
           
$c = count($new_haystack);
           
$r = binSearch($needle, $new_haystack);
           
// return current index - (length of lower half - found index in lower half)
           
return $m - ($c - $r);
            break;
        }
        case(
$compare<$needle):
        {
           
// recurse on the upper half
           
$new_haystack = array_slice($haystack, $m, ($l-$m));
           
$c = count($new_haystack);
           
$r = binSearch($needle, $new_haystack);
           
// return current position + found index in upper half
           
return $m + $r;
            break;
        }
        case(
$compare==$needle):
        {
           
// found it, so return index
           
return $m;
            break;
        }
    }
}
?>

helenadeus at gmail dot com

14 years ago


I was trying to use array_search to retrieve all the values that match a given needle, but it turns out only the first match key is returned. I built this little function, which works just like array_search, but returns all the keys that match a given needle instead. The output is an array.

<?php

$haystack

= array('a','b','a','b');$needle = 'a';print_r(array_search_all($needle, $haystack));//Output will be
// Array
// (
//         [0]=>1
//         [1]=>3
// )
function array_search_all($needle, $haystack)
{
#array_search_match($needle, $haystack) returns all the keys of the values that match $needle in $haystackforeach ($haystack as $k=>$v) {

            if(

$haystack[$k]==$needle){$array[] = $k;
        }
    }
    return (
$array);

    }

?>


nordseebaer at gmx dot de

3 years ago


It's really important to check the return value is not false! I used array_search() to determine the index of an value to unset this value and then realized that $arr[false] === $arr[0] !

<?php
$arr
= ['apple', 'banana'];var_dump($arr[0] === 'apple'); // true
var_dump($arr[false] === $arr[0]); // true
var_dump($arr[false] === 'apple'); // trueunset($arr[array_search('banana', $arr)]); //index = 1
var_dump($arr);// result
//   array(1) {
//     [0]=>
//     string(5) "apple"
//   }
unset($arr[array_search('peach', $arr)]); //not found, result is false
var_dump($arr);// result
//   array(0) {
//   }
// because $arr[false] === $arr[0]
?>

So always check the return of array_search!


kermes [at] thesevens [dot] net

15 years ago


A variation of previous searches that returns an array of keys that match the given value:

<?php
function array_ksearch($array, $str)
{
   
$result = array();
    for(
$i = 0; $i < count($array); next($array), $i++)
        if(
strtolower(current($array)) == strtolower($str))
           
array_push($result, key($array);

        return

$result;
}
?>

Usage would be as follows:
<?php
$testArray
= array('one' => 'test1', 'two' => 'test2', 'three' => 'test1', 'four' => 'test2', 'five' => 'test1');
   
print_r(array_ksearch($testArray, 'test1'));
?>


I’m wondering if there’s a known, built-in/elegant way to find the first element of a JS array matching a given condition. A C# equivalent would be List.Find.

So far I’ve been using a two-function combo like this:

// Returns the first element of an array that satisfies given predicate
Array.prototype.findFirst = function (predicateCallback) {
    if (typeof predicateCallback !== 'function') {
        return undefined;
    }

    for (var i = 0; i < arr.length; i++) {
        if (i in this && predicateCallback(this[i])) return this[i];
    }

    return undefined;
};

// Check if element is not undefined && not null
isNotNullNorUndefined = function (o) {
    return (typeof (o) !== 'undefined' && o !== null);
};

And then I can use:

var result = someArray.findFirst(isNotNullNorUndefined);

But since there are so many functional-style array methods in ECMAScript, perhaps there’s something out there already like this? I imagine lots of people have to implement stuff like this all the time…

asked May 4, 2012 at 23:14

Jakub P.'s user avatar

6

Since ES6 there is the native find method for arrays; this stops enumerating the array once it finds the first match and returns the value.

const result = someArray.find(isNotNullNorUndefined);

Old answer:

I have to post an answer to stop these filter suggestions :-)

since there are so many functional-style array methods in ECMAScript, perhaps there’s something out there already like this?

You can use the some Array method to iterate the array until a condition is met (and then stop). Unfortunately it will only return whether the condition was met once, not by which element (or at what index) it was met. So we have to amend it a little:

function find(arr, test, ctx) {
    var result = null;
    arr.some(function(el, i) {
        return test.call(ctx, el, i, arr) ? ((result = el), true) : false;
    });
    return result;
}
var result = find(someArray, isNotNullNorUndefined);

answered Aug 29, 2013 at 20:20

Bergi's user avatar

BergiBergi

620k145 gold badges947 silver badges1365 bronze badges

12

As of ECMAScript 6, you can use Array.prototype.find for this. This is implemented and working in Firefox (25.0), Chrome (45.0), Edge (12), and Safari (7.1), but not in Internet Explorer or a bunch of other old or uncommon platforms.

For example, x below is 106:

const x = [100,101,102,103,104,105,106,107,108,109].find(function (el) {
    return el > 105;
});
console.log(x);

If you want to use this right now but need support for IE or other unsupporting browsers, you can use a shim. I recommend the es6-shim. MDN also offers a shim if for some reason you don’t want to put the whole es6-shim into your project. For maximum compatibility you want the es6-shim, because unlike the MDN version it detects buggy native implementations of find and overwrites them (see the comment that begins «Work around bugs in Array#find and Array#findIndex» and the lines immediately following it).

answered Feb 3, 2014 at 23:33

Mark Amery's user avatar

Mark AmeryMark Amery

140k78 gold badges402 silver badges457 bronze badges

1

What about using filter and getting the first index from the resulting array?

var result = someArray.filter(isNotNullNorUndefined)[0];

Dan Dascalescu's user avatar

answered Aug 28, 2013 at 15:54

Phil Mander's user avatar

Phil ManderPhil Mander

1,81915 silver badges20 bronze badges

5

Summary:

  • For finding the first element in an array which matches a boolean condition we can use the ES6 find()
  • find() is located on Array.prototype so it can be used on every array.
  • find() takes a callback where a boolean condition is tested. The function returns the value (not the index!)

Example:

const array = [4, 33, 8, 56, 23];

const found = array.find(element => {
  return element > 50;
});

console.log(found);   //  56

Leniel Maccaferri's user avatar

answered Aug 19, 2018 at 11:46

Willem van der Veen's user avatar

2

It should be clear by now that JavaScript offers no such solution natively; here are the closest two derivatives, the most useful first:

  1. Array.prototype.some(fn) offers the desired behaviour of stopping when a condition is met, but returns only whether an element is present; it’s not hard to apply some trickery, such as the solution offered by Bergi’s answer.

  2. Array.prototype.filter(fn)[0] makes for a great one-liner but is the least efficient, because you throw away N - 1 elements just to get what you need.

Traditional search methods in JavaScript are characterized by returning the index of the found element instead of the element itself or -1. This avoids having to choose a return value from the domain of all possible types; an index can only be a number and negative values are invalid.

Both solutions above don’t support offset searching either, so I’ve decided to write this:

(function(ns) {
  ns.search = function(array, callback, offset) {
    var size = array.length;

    offset = offset || 0;
    if (offset >= size || offset <= -size) {
      return -1;
    } else if (offset < 0) {
      offset = size - offset;
    }

    while (offset < size) {
      if (callback(array[offset], offset, array)) {
        return offset;
      }
      ++offset;
    }
    return -1;
  };
}(this));

search([1, 2, NaN, 4], Number.isNaN); // 2
search([1, 2, 3, 4], Number.isNaN); // -1
search([1, NaN, 3, NaN], Number.isNaN, 2); // 3

Community's user avatar

answered Sep 17, 2013 at 4:57

Ja͢ck's user avatar

Ja͢ckJa͢ck

170k38 gold badges263 silver badges309 bronze badges

1

If you’re using underscore.js you can use its find and indexOf functions to get exactly what you want:

var index = _.indexOf(your_array, _.find(your_array, function (d) {
    return d === true;
}));

Documentation:

  • http://underscorejs.org/#find
  • http://underscorejs.org/#indexOf

answered Sep 17, 2013 at 3:12

Matt Woelk's user avatar

Matt WoelkMatt Woelk

1,9101 gold badge19 silver badges24 bronze badges

1

As of ES 2015, Array.prototype.find() provides for this exact functionality.

For browsers that do not support this feature, the Mozilla Developer Network has provided a polyfill (pasted below):

if (!Array.prototype.find) {
  Array.prototype.find = function(predicate) {
    if (this === null) {
      throw new TypeError('Array.prototype.find called on null or undefined');
    }
    if (typeof predicate !== 'function') {
      throw new TypeError('predicate must be a function');
    }
    var list = Object(this);
    var length = list.length >>> 0;
    var thisArg = arguments[1];
    var value;

    for (var i = 0; i < length; i++) {
      value = list[i];
      if (predicate.call(thisArg, value, i, list)) {
        return value;
      }
    }
    return undefined;
  };
}

answered May 2, 2016 at 18:48

Kevin Lee Garner's user avatar

0

foundElement = myArray[myArray.findIndex(element => //condition here)];

answered Apr 4, 2019 at 9:29

Dotista's user avatar

DotistaDotista

3862 silver badges12 bronze badges

1

answered Feb 22, 2016 at 16:28

Dan Ochiana's user avatar

Dan OchianaDan Ochiana

3,3001 gold badge30 silver badges27 bronze badges

0

Use findIndex as other previously written. Here’s the full example:

function find(arr, predicate) {
    foundIndex = arr.findIndex(predicate);
    return foundIndex !== -1 ? arr[foundIndex] : null;
}

And usage is following (we want to find first element in array which has property id === 1).

var firstElement = find(arr, e => e.id === 1);

answered Nov 6, 2020 at 8:46

michal.jakubeczy's user avatar

michal.jakubeczymichal.jakubeczy

7,9571 gold badge57 silver badges61 bronze badges

I have got inspiration from multiple sources on the internet to derive into the solution below. Wanted to take into account both some default value and to provide a way to compare each entry for a generic approach which this solves.

Usage: (giving value «Second»)

var defaultItemValue = { id: -1, name: "Undefined" };
var containers: Container[] = [{ id: 1, name: "First" }, { id: 2, name: "Second" }];
GetContainer(2).name;

Implementation:

class Container {
    id: number;
    name: string;
}

public GetContainer(containerId: number): Container {
  var comparator = (item: Container): boolean => {
      return item.id == containerId;
    };
    return this.Get<Container>(this.containers, comparator, this.defaultItemValue);
  }

private Get<T>(array: T[], comparator: (item: T) => boolean, defaultValue: T): T {
  var found: T = null;
  array.some(function(element, index) {
    if (comparator(element)) {
      found = element;
      return true;
    }
  });

  if (!found) {
    found = defaultValue;
  }

  return found;
}

answered Aug 7, 2019 at 16:49

Henrik's user avatar

HenrikHenrik

1,8671 gold badge16 silver badges9 bronze badges

      const employees = [
        {id: 1, name: 'Alice', country: 'Canada'},
        {id: 2, name: 'Bob', country: 'Belgium'},
        {id: 3, name: 'Carl', country: 'Canada'},
        {id: 4, name: 'Dean', country: 'Germany'},
      ];
    
      // 👇️ filter with 1 condition
      const filtered = employees.filter(employee => {
        return employee.country === 'Canada';
      });
      // 👇️ [{id: 1, name: 'Alice', country: 'Canada'},
      //     {id: 3, name: 'Carl', 'country: 'Canada'}]
      console.log(filtered);
    
      // 👇️ filter with 2 conditions
      const filtered2 = employees.filter(employee => {
        return employee.country === 'Canada' && employee.id === 3;
      });
    
      // 👇️ [{id: 3, name: 'Carl', country: 'Canada'}]
      console.log('filtered2: ', filtered2);
    
      const employee = employees.find(obj => {
    return obj.country === 'Canada';
  });

  // 👇️ {id: 1, name: 'Alice', country: 'Canada'}
  console.log(employee);

answered Dec 6, 2022 at 6:24

Engr.Aftab Ufaq's user avatar

Engr.Aftab UfaqEngr.Aftab Ufaq

2,8223 gold badges19 silver badges42 bronze badges

There is no built-in function in Javascript to perform this search.

If you are using jQuery you could do a jQuery.inArray(element,array).

Eranga's user avatar

Eranga

32.1k5 gold badges97 silver badges96 bronze badges

answered May 4, 2012 at 23:22

PedroSena's user avatar

PedroSenaPedroSena

6456 silver badges14 bronze badges

3

A less elegant way that will throw all the right error messages (based on Array.prototype.filter) but will stop iterating on the first result is

function findFirst(arr, test, context) {
    var Result = function (v, i) {this.value = v; this.index = i;};
    try {
        Array.prototype.filter.call(arr, function (v, i, a) {
            if (test(v, i, a)) throw new Result(v, i);
        }, context);
    } catch (e) {
        if (e instanceof Result) return e;
        throw e;
    }
}

Then examples are

findFirst([-2, -1, 0, 1, 2, 3], function (e) {return e > 1 && e % 2;});
// Result {value: 3, index: 5}
findFirst([0, 1, 2, 3], 0);               // bad function param
// TypeError: number is not a function
findFirst(0, function () {return true;}); // bad arr param
// undefined
findFirst([1], function (e) {return 0;}); // no match
// undefined

It works by ending filter by using throw.

answered Aug 29, 2013 at 18:46

Paul S.'s user avatar

Paul S.Paul S.

64.4k9 gold badges120 silver badges138 bronze badges

  • Главная

  • Инструкции

  • JavaScript

  • Методы поиска в массивах JavaScript

Blog

Поиск в массиве — довольно несложная задача для программиста. На ум сразу приходит перебор через цикл for или бинарный поиск в отсортированном массиве, для элементов которого определены операции «больше» и «меньше». Но, как и любой высокоуровневый язык программирования, JavaScript предлагает разработчику встроенные функции для решения различных задач. В этой статье мы рассмотрим четыре метода поиска в массивах JavaScript: find, includes, indexOf и filter.

Методы Поиска В Массивах Java Script (1)

indexOf

indexOf — это функция поиска элемента в массиве. Этот метод с помощью перебора ищет искомый объект и возвращает его индекс или «-1», если не находит подходящий.

Синтаксис

Функция имеет такой синтаксис:

Array.indexOf (search element, starting index)

где:

  • Array — массив;
  • search element — элемент, который мы ищем;
  • starting index — индекс, с которого начинаем перебор. Необязательный аргумент, по умолчанию работа функции начинается с индекса “0”, т.е. метод проверяет весь Array. Если starting index больше или равен Array.length, то метод сразу возвращает “-1” и завершает работу. 

Если starting index отрицательный, то JS трактует это как смещение с конца  массива: при starting index = “-1” будет проверен только последний элемент, при “-2” последние два и т.д. 

Практика

Опробуем метод на практике. Запустим такой код и проверим результаты его работы:

let ExampleArray = [1,2,3,1,'5', null, false, NaN,3];

console.log("Позиция единицы", ExampleArray.indexOf(1) );
console.log("Позиция следующей единицы", ExampleArray.indexOf(1,2) );
console.log("Позиция тройки", ExampleArray.indexOf(3) );
console.log("Позиция тройки, если starting index отрицательный", ExampleArray.indexOf(3,-2) );
console.log("Позиция false", ExampleArray.indexOf(false) );
console.log("Позиция 5", ExampleArray.indexOf("5") ); 
console.log("Позиция NaN", ExampleArray.indexOf(NaN));

В результате работы этого кода мы получили такой вывод: 

Позиция единицы 0
Позиция следующей единицы 3
Позиция тройки 2
Позиция тройки, если starting index отрицательный 8
Позиция false 6
Позиция 5 -1
Позиция NaN -1

indexOf осуществляет поиск элемента в массиве слева направо и останавливает свою работу на первом совпавшем. Отчетливо это проявляется в примере с единицей. Для того, чтобы идти справа налево, используйте метод LastIndexOf с аналогичным синтаксисом.

Для сравнения искомого и очередного объекта применяется строгое сравнение (===). При использовании строгого сравнения для разных типов данных, но с одинаковым значение, например 5, ‘5’ и “5” JavaScript даёт отрицательный результат, поэтому IndexOf не нашел 5. 

Также стоит помнить, что indexOf некорректно обрабатывает NaN. Так что для работы с этим значением нужно применять остальные методы.

includes

includes не совсем проводит поиск заданного элемента в массиве, а проверяет, есть ли он там вообще. Работает он примерно также как и indexOf. В конце работы includes возвращает «True», если нашел искомый объект, и «False», если нет. Также includes правильно обрабатывает NaN

Синтаксис

includes имеет следующий синтаксис:

Array.includes (search element, starting index)

где: 

  • Array — массив;
  • search element — элемент, который мы ищем;
  • starting index — индекс, с которого начинаем перебор. Необязательный аргумент, по умолчанию работа функции начинается с индекса “0”, т.е. метод проверяет весь Array. Если starting index больше или равен Array.length, то метод сразу возвращает «False» и завершает работу.  

Если starting index отрицательный, то JS трактует это как смещение с конца массива: при starting index = “-1” будет проверен только последний элемент, при “-2” последние два и т.д.  

Практика

Немного изменим код из предыдущего примера и запустим его:

let Example = [1,2,3,1,'5', null, false,NaN, 3];

console.log("Наличие единицы", Example.includes(1) );
console.log("Наличие следующей единицы", Example.includes(1,2) );
console.log("Наличие тройки", Example.includes(3) );
console.log("Наличие тройки, если starting index отрицательный", Example.includes(3,-1) );
console.log("Наличие false", Example.includes(false) );
console.log("Наличие 5", Example.includes(5) ); 
console.log("Наличие NaN", Example.includes(NaN));

Вывод:

Наличие единицы true
Наличие следующей единицы true
Наличие тройки true
Наличие тройки, если starting index отрицательный true
Наличие false true
Наличие 5 false
Наличие NaN true

Для includes отсутствует альтернативная функция, которая проводит поиск по массиву js справа налево, которая, в общем-то, и не очень актуальна.

find

Предположим, что нам нужно найти в массиве некий объект. Но мы хотим найти его не по значению, а по его свойству. Например, поиск числа в массиве со значением между 15 и 20. Как и прежде, мы можем воспользоваться перебором с помощью for, но это не слишком удобно. Для поиска с определенным условием в JavaScript существует метод find.

Синтаксис

Array.find(function(...){
//если элемент соответствует условиям (true), то функция возвращает его  и прекращает работу;
//если ничего не найдено, то возвращает undefined
})
  • Array — массив;
  • function(…) — функция, которая задает условия.

Практика

Как и в прошлых примерах, напишем небольшой код и опробуем метод:

let ExampleArray = ["Timeweb", 55555, "Cloud", "облачный провайдер", "буквы"];

console.log(ExampleArray.find(element => element.length == 5))

Вывод:

Cloud

В этом примере мы искали строки с длиной в 5 символов. Для числовых типов данных длина не определена, поэтому 55555 не подходит. find находит первый элемент и возвращает его, поэтому «буквы» также не попали в результат работы нашей функции. Для того, чтобы найти несколько элементов, соответствующих некоторому условию, нужно использовать метод filter.

Также не стоит забывать о методе findIndex. Он возвращает индекс подходящего элемента. Или -1, если его нет. В остальном он работает точно также, как и find.

filter

find ищет и возвращает первый попавшийся элемент, соответствующий условиям поиска. Для того, чтобы найти все такие элементы, необходимо использовать метод filter. Результат этой функции — массив (если ничего не найдено, то он будет пустым).

Синтаксис

Array.find(function(...){
//если элемент соответствует условиям (true), то добавляем его к конечному результату и продолжаем перебор;
})
  • Array — массив;
  • function(…) — функция, которая задает условия.

Практика

Представим следующую задачу: у нас есть список кубоидов (прямоугольных параллелепипедов) с длинами их граней и нам нужно вывести все кубоиды с определенным объемом. Напишем код, реализующий решение данной задачи:

let ExampleArray = [
  [10, 15, 8],
  [11, 12, 6],
  [5, 20, 1],
  [10, 10, 2],
  [16,2, 4]
  ];

console.log(ExampleArray.filter(element=> element[0]*element[1]*element[2]>300))

 Вывод:

[ [ 10, 15, 8 ],
 [ 11, 12, 6 ] ]

В этом примере мы нашли прямоугольные параллелепипеды с объемом больше 300. В целом, метод filter в JS позволяет реализовывать всевозможные условия для поиска. 

Заключение

В этой статье узнали о методах поиска в JavaScript и научились ими пользоваться. Все перечисленные методы — универсальные инструменты для разработчиков. Но, как и любые универсальные инструменты, они не всегда являются самыми производительными. Так, например, бинарный поиск будет куда эффективнее, чем find и filter.

Вообщем то, что у меня получилось ниже логика скрипта должна быть такая:

  • 1.Пользователь забивает в форму контакты (просто емайл контакты или контакты емайл:пароль или какая то другая вариация контактов. Скрипт разбивает это все на массивы и выявляет емаейлы и отделяет ненужное удаляя дубликаты. Сохраняет в файл все это дело.
  • 2.Страница генерации позволяет сгенерировать базу из сохраненного файла по параметрам начального символа и конечного символа, а так же по домену и возможность скачать сгенерированный файл.
  • 3.Страница позволяет отправить от указанного имени с темой и контентом письма всей базе сгенерированного файла.

Вот, что из этого получилось:

PS! не пинайте за быдло код лудше подправьте, что не так в нормальный код

class eMails extends mail
{

    protected $tmpFolder = "temp.txt";
    protected $genFolder = "generated.txt";

    function __construct($exec_time = 1600)
    {
        session_start();
        ini_set('max_execution_time', $exec_time); //300 seconds = 5 minutes
        header('Content-Type: text/html; charset=utf-8');
        ini_set('display_errors',1);
        error_reporting(E_ALL);
        setlocale(LC_CTYPE, 'us_US.UTF8');

        // Проверяем существуют папки для работы 

        if (!file_exists($this->tmpFolder)){
            $fh = fopen($newfile, 'w') or die("Невозможно ");
            fclose($fh);
        }

    }

    private function checkFiles($whatCheck=false){

        // Проверяем на существование и пустоту файл
        if (!file_exists($whatCheck) || '' == filesize($whatCheck)) {
            return false;
        } 
        return true;
    }

    private function getData($string=false,$getFromFile=false){

        if ($getFromFile)
            $string = file_get_contents($string);

        $array = array_filter(explode("n", $string));

        if (count($array) < 1) {
            echo "Массив пустой, нечего обрабатывать!";
            return false;
        } 

        return $array;
    }

    public function addNewMails(){

        $count_processed= 0;

        if ($_SERVER['REQUEST_METHOD'] == "POST") {

            /* Обрабатываем залитый файл и генерируем новый файл по определенному параметру */ 
            // Удаляем пустые массивы
            $_POST = array_filter($_POST);

            if ( !array_key_exists("data2load", $_POST) || empty($_POST['data2load'])) {
                die("<h3>Нет нужного параметра, выхожу...</h3>");
            }

            $_POST['data2load'] = htmlspecialchars($_POST['data2load']);

            // Создаем массив с емайлами
            //$tmp = explode("n", $_POST['data2load']);

            $tmp = $this->getData($_POST['data2load']);

            // Проверяем массив 
            if ($tmp != false) {

                /* Устанавливаем разделитель */
                $delimiter = !empty($_POST['delimiter']) ? $_POST['delimiter'] : false;

                // Записываем переменные в массив
                foreach ($tmp as $key => $value) {
                    // Автоматически определить как разделитель стоит или стоит он вообще или нет

                    $t = $delimiter != false ? strstr(str_replace(" ", " _ ", $value), $delimiter, true) : $value; 

                    if ( filter_var($t, FILTER_VALIDATE_EMAIL) ) {
                        file_put_contents($this->tmpFolder, $t."n", FILE_APPEND | LOCK_EX);    
                        $count_processed++;
                    } 
                }
                echo "<hr> Найдено емайлов: { $count_processed }";
            } else {
                echo "<p>Пустой массив данных!</p>";
                //var_dump($tmp);
            }


        } else {
            ?>
            <form action="?action=new" method="POST" enctype="multipart/form-data">
                <h3>Upload emails</h3>
                <p><textarea name="data2load" cols="45" rows="25" placeholder="Put here emails"></textarea></p>
                <p>
                <label>Разделитель который используется для емайла и пароля</label><br>
                <select name="delimiter">
                    <option value=":">:</option>
                    <option value=";">;</option>
                    <option value="_" selected>Пробел как разделитель</option>
                    <option>Разделителя нету</option>
                </select></p>
                <p>Удалить дубликаты<input type="checkbox" name="removeDublicates" /></p>
                <input type="submit" name="submit" value="Добавить емайлы" />
            </form>
            <?php 
        }
    }

    public function generateEmaildb(){

        if ($_SERVER['REQUEST_METHOD'] == "POST") {

            // Фильтры по умолчанию пустые 
            $begin = false;
            $end   = false;
            $domain= false;

            // имя для сохранения сгенерированной информации пустое
            $fileName = "";

            $recordedEmails = 0;

            if (!empty($_POST['filterBegin'])) {

                $fileName .= $_POST['filterBegin'];
                $begin = true;
            }
            if (!empty($_POST['filterEnd'])) {

                $fileName .= $_POST['filterEnd'];
                $end = true;
            }
            if (!empty($_POST['filterDomen'])) {

                $fileName .= $_POST['filterDomen'];
                $domain = true;
            }

            $fileName = !$fileName ? "generated_automaticaly.txt" : $fileName.".txt";

            $_SESSION['generated'] = $fileName;

            // Файл сохранять по параметрам заданым пользователями . всего 3 видами параметров.

            $tmp = $_SESSION['tmp'];

            if (!$this->checkFiles($tmp)) {
                echo "<p> Файл с базой емайлов отсутсвует</p>";
                return false;
            }

            $tmp = $this->getData($tmp,true);

            if (!$tmp)
                return false;

            foreach ($tmp as $key => $value) {

                $recordEmail = true;

                // Проверяем фильтры указанные пользователем, если хоть один указанный пользователем не сработал
                // то запись не записывается !!!
                if ($begin != false) {
                    if ($value{0} != mb_strtoupper($begin,'UTF-8') || $value{0} != mb_strtolower($begin,'UTF-8') ) {
                        $recordEmail = false;
                    }
                }
                if ($end != false) {

                    $m = strstr($value, "@", true);
                    if (substr($m, -1) != mb_strtoupper($end,'UTF-8') || substr($m, -1) != mb_strtolower($end,'UTF-8')) {
                        $recordEmail = false;
                    }

                }
                if ($domain != false) {
                    //"^[d|D]S*@[g|G]?[m|M][a|A][i|I][l|L].[r|R][u|U]$" // для preg_match
                    if (strstr($value, '@') != '@'.mb_strtolower($domain,'UTF-8')) {
                        $recordEmail = false;
                    }
                }

                // Записываем в файл отфильтрованное значение
                if ($recordEmail != false) {
                    file_put_contents($fileName, $value."n", FILE_APPEND | LOCK_EX);
                    $recordedEmails++;
                }
            }

            echo "<p>Записей { $recordedEmails } в файле { $fileName } </p>";
            echo "<p><form action='?download=getFile' method='POST' target='_blank'><input type='submit' name='downloadFile' value='Скачать файл' /></form></p>";

        } else {

            $tmp = $this->checkFiles($_SESSION['tmp'],true);
            if (!$tmp) {
                echo "<p>Сперва нужно создать базу с емайлами</a>";
            } else {
            ?>
                <form action="?action=gen" method="POST" >
                    <h3>Параметры для генерации базы емайлов</h3>
                    <label>Пустые поля игнорируются!</label>
                    <p><input type="text" name="filterBegin" placeholder="Первый символ емайла. Пр: A,*,a,_" /></p>
                    <p><input type="text" name="filterEnd" placeholder="Последний символ до значка @. Пр: A,*,a,_" /></p>
                    <p><input type="text" name="filterDomen" placeholder="Укажите домен для фильтрации" /></p>
                    <input type="submit" name="genFilterDB" value="Сгенерировать базу"> <br><span style="color: red">OR</span> <br>
                    <input type="submit" name="removeDublicate" value="Удалить дубликаты">
                </form>
                <?php 
            }
        }
    }

    public function sendEmailDestination(){

        // Проверяем файл на существование

        $tmp = $this->getData($_SESSION['generated']);

        if ($_SERVER['REQUEST_METHOD'] == "POST" && count($tmp) > 0) {

            if ( empty($_POST['from']) or empty($_POST['subject']) or empty($_POST['content'])) {
                echo "<p>Есть пустые поля! Не могу продолжать, выхожу из скрипта</p>";
                return false;
            }

            $sendFrom    = $_POST['from'];
            $sendSubject = $_POST['subject'];
            $sendContent = $_POST['content'];           

            $emailsended = 0;

            foreach ($tmp as $key => $value) {

                //mail::sendMail($value, $sendSubject, $sendContent, $sendFrom);
                $emailsended++;
            }

            echo "<p>Кол-во емайлов отправленно: { $emailsended }</p>";

        } else {

            if (!$tmp) {
                echo "<h3 style='color: green;'>Cперва нужно сгенерировать файл-базу емайлов!</h3>";
            } else {
                ?>
                <form>
                    <p><input type="text" name="from" placeholder="Автор: ваш емайл" /></p>
                    <p><input type="text" name="subject" placeholder="Тема сообщения" /></p>    
                    <p><textarea name="content" placeholder="Тело сообщения" cols="45" rows="25"></textarea></p>
                    <p><input type="submit" name="submit" value="Отослать письма сгенерированной базе!" /></p>  
                </form>
                <?php           
            }
        }

    }

    public function removeDublicate() { 

        $tmp = $_SESSION['temp'];

        $tmp = $this->getData($tmp,true);


        foreach ($tmp as $key => $value_result) {

        }
    }



    public function getFile($what2download=false) {

        $file = $_SESSION['generated'];

        if (isset($_GET['download']) && $file != false) {

            header('Content-Description: File Transfer');
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename="'.basename($file).'"');
            header('Expires: 0');
            header('Cache-Control: must-revalidate');
            header('Pragma: public');
            header('Content-Length: ' . filesize($file));
            readfile($file);
        }
    }


}

Помогите мне исправить недочеты и быдло код

Поиск в массиве предусмотрен во многих языках программирования, в том числе и в С. Поиск является видом обработки данных в массиве с целью определения и выявления элемента, который соответствует заданным критериям. Поиск в массиве элемента на С разделяют на 2 большие категории:

  • поиск в несортированном массиве;

  • поиск в сортированном массиве.

То есть поиск и сортировка в массиве идут тесно рядом. Сортировкой называют специальный процесс, при котором элементы в массиве переставляются по какому-либо критерию или свойству. Например, если в массиве содержатся цифровые данные, то можно осуществить сортировку по возрастанию или убыванию, — это приведет к тому, что элементы в массиве будут располагаться упорядоченно. Главная цель любой сортировки — облегчить работу с элементами массива, например облегчить поиск в массиве.

Поиск элемента в массиве на С

Поиск в массиве на С можно осуществить несколькими методами, каждый из которых отличается своими характеристиками. На сегодня существует достаточно много разнообразных алгоритмов поиска, самыми распространенными из них являются:

  • линейный поиск в массиве на С;

  • двоичный или бинарный поиск в массиве на С;

  • интерполирующий поиск на С.

Есть и другие методы, но, если изучить эти — их будет вполне достаточно, чтобы найти нужный элемент в массиве.

Линейный поиск элемента в массиве на С

Линейный поиск в массиве на С является самым простым алгоритмом, поэтому изучается первым. Суть его заключается в том, что необходимо будет «перебирать» все элементы массива на совпадение с заданными критериями или ключами. Самый простой не означает самый быстрый. Этот вид поиска очень затратный по времени, поэтому не рекомендуется к применению в массивах с большим количеством данных.

Пример функции линейного поиска:

int linSearch(int arr[], int requiredKey, int arrSize)

{

 for (int i = 0; i < arrSize; i++)

 {

 if (arr[i] == requiredKey)

 return i;

 }

 return -1;

}

Данный вид поиска подходит для поиска одиночного элемента в небольших несортированных массивах. Если массив большой, тогда лучше отсортировать его и применить один из методов, описанных ниже.

Двоичный или бинарный поиск элемента в массиве на С

Бинарный поиск в массиве на С подходит для отсортированных массивов. Он также считается довольно простым, но при этом более эффективным, чем линейный алгоритм. Алгоритм его работы основывается на делении массива «пополам» и сверки среднего значения с заданным ключом. Например:

  1. Допустим, у вас есть отсортированный массив с простыми числами от 1 до 10: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].

  2. Вам необходимо найти индекс значения числа «2». «2» будет ключом поиска, поэтому на первом этапе массив поделится «пополам». Так как индексирование элементов в массиве начинается с 0, у нас получается, что 0 + 9 / 2 = 4 (0,5 отбрасывается, и индекс округляется). Под индексом 4 у нас стоит число 5, это число сравнивается с нашим ключом. 5 не равно 2 и больше него. Если бы «среднее» значение массива совпало с ключом, тогда массив бы прекратил работу.

  3. Так как 5 больше 2, поиск значения продолжится в части массива, содержащей числа от 1 до 5, а числа от 6 до 10 «отбрасываются в сторону». Вторым шагом алгоритма будет поиск среднего значения в «укороченном» массиве: 0 + 4 / 2 = 2. Под индексом 2 у нас расположено число 3. 3 сравнивается с ключом. Алгоритм определит, что 3 не равно 2 и больше него. Значит, будет третий шаг.

  4. На третьем шаге еще часть массива после числа 3 «отбрасывается». Алгоритм ищет среднее значение в оставшихся индексах: 0 + 2 / 2 = 1. Под индексом 1 у нас располагается число 2, это число сравнивается с нашим ключом. Алгоритм определяет, что число 2 равно нашему ключу 2, выдает нам соответствующий индекс числа и заканчивает свою работу.

Вот как все, что мы описали выше, выглядит в скрипте:

#include <iostream>

using namespace std;

int SearchingAlgorithm (int arr[], int left, int right, int keys)

{

int middle = 0;

while (1)

{

middle = (left +right) / 2;

if (keys < arr[middle])

right = middle -1;

else if (keys > arr[])

left = middle + 1;

else

return middle;

if (left > right)

return -1;

}

}

int main()

{

  selocale (LC_ALL, “rus“);

  const int SIZE = 10;

  int array[SIZE] = {};

  int keys = 0;

  int index = 0;

  for (int i = 0; i < SIZE; i++)

  {

   array[i] = i +1;

  cout < < array[i] < <  “ | “;

  cout < < “nn Необходимо ввести числовое значение для поиска: “;

  cin > > keys;

  index = SearchingAlgorithm (array, 0, SIZE, keys);

  if (index >= 0)

  cout < < “Значение, которое вы указали, располагается с порядковым индексом: “ < < index < < “nn“;

  else

  cout < < “Введенное значение в массиве не обнаружено!nn“;

  return 0;

}

Если запустить программу, тогда получится следующий результат:

Необходимо ввести числовое значение для поиска: 2

Значение, которое вы указали, располагается с порядковым индексом: 1

Поиск в массиве С бинарным алгоритмом хорош тем, что он работает намного быстрее, чем линейный алгоритм. Представим, что вам необходимо осуществить поиск в массиве, содержащем 1000 элементов. Линейный поиск должен будет обойти все элементы, а бинарный около 10. Такой результат возможен, потому что при каждом определении среднего значения часть массива, где точно нет искомого значения, просто отсеивается. Например, при первом шаге в массиве с 1000 элементов 500 отсеются, при втором еще 250 и т. д.

Самая главная проблема бинарного поиска заключается в том, что он работает только в отсортированных и упорядоченных массивах.

Интерполирующий поиск элемента в массиве С

Интерполирующий поиск пришел из математики, и он не настолько сложен, как произносится. Его смысл сводится к тому, что необходимо определять область поиска заданного значения, вычисляя подобие расстояний между искомым элементом и всей областью. Как это выглядит в коде:

#include <iostream>

using namespace std;

int main ()

{

//Определяем массив со значениями, среди которых будет проходить поиск

int OwnArray [] {2, 3, 5, 7, 8, 90, 124, 232, 1001, 1236 };

int y = 0; //определяем текущую позицию массива

int c = 0; //определяем левую границу массива, откуда будет начинаться поиск

int d = 9; //определяем правую границу массива, докуда будет продолжаться поиск

int WeSearch = 124; //определяем элемент, который ищем

bool found;

//Запускаем интерполяционный поиск в массиве С

for (found = false; (OwnArray[c] < WeSearch) && (OwnArray[d] > WeSearch) && | found;)

y = c + ((WeSearch — OwnArray[c]) * (d — c)) / (OwnArray[d] — OwnArray[c]);

if (OwnArray[y] < WeSearch)

c = y +1;

else if (OwnArray[y] > WeSearch)

d = y -1;

else

found = true;

}

//интерполяционный поиск в массиве окончен, тогда можно вывести результаты 

if (OwnArray[c] == We Search)

cout < < WeSearch < < “Элемент найден“ < < c < < endl;

else if (OwnArray[d] == WeSearch)

cout < < WeSearch < < “Элемент найден“ < < d < < endl;

else

cout < < “Извините, элемент не найден“ < < endl;

return 0;

}

Простыми словами: этот метод вычисляет область, где может быть расположен искомый элемент; если в этой области нет элемента, тогда границы области в массиве сдвигаются в ту или иную сторону. Этот метод чем-то похож на бинарный алгоритм, потому что в нем также «куски» массива постепенно отсеиваются, пока искомая область не будет сужена до 1 элемента. Если и в этом случае искомый элемент не будет найден, тогда его нет в массиве.

Заключение

Поиск элемента в массиве С можно осуществить и другими алгоритмами, например, используя:

  • «Решето Эратосфена»;

  • поиск с «барьером»;

  • и другие алгоритмы.

Каждый из них посвоему хорош, но описанных выше алгоритмов достаточно для понимания стратегии поиска. Ведь даже их можно модифицировать посвоему, адаптируя под собственную задачу.

Понравилась статья? Поделить с друзьями:
  • Статусы как найти брата
  • Как исправить тоскую по вам
  • Как найти платного психиатра
  • Как найти управу на поликлинику
  • Как найти гусей видео