binary search in an array in Perl

后端 未结 2 2097
盖世英雄少女心
盖世英雄少女心 2020-12-14 12:08

I have an array of hex numbers, and I need to go over other numbers and check if they appear in that array. Right now i\'m using a foreach loop that goes over t

2条回答
  •  孤街浪徒
    2020-12-14 12:51

    If you're just going to do one search, then sorting will take longer than performing a single linear scan, so you may as well just stick with looping over the array. For a small array, or if you could have multiple matches, you might also want to look at the grep function; it's a little easier to use, but it will always check the entire list of candidate matches instead of stopping when a match is found.

    If you're going to be searching many times, putting the array's values into a hash and doing hash lookups will be faster than searching the array, even if you sort it and do a binary search (assuming you can afford the memory cost, but you almost certainly can).

提交回复
热议问题