Your algorithm for the search must meet certain requirements:
correctness - it must return the correct results that are being sought, every time
applicability - it must be appropriate for the source type and data needs
- 因为搜索的对象可能是 Excel、XML、JSON 或关系型数据库等
speed - it must execute in a timely manner based on your requirements for searching
Linear Search
The basic through process in a linear search is this:
set a counter equal to 0
check the item at position (counter) and if it equals search term, end the algorithm
if search term is not found in step 2, increment counter and repeat step 2
static void LineSearchDemo()
{
// declare an array of integers that will be used for searching
int[] searchArray = { 5, 10, 3, 2, 4 };
int term = 2;
int index = LinearSearch(searchArray, term);
if (index != -1)
{
Console.WriteLine($"Your search term was found at position {index}");
}
else
{
Console.WriteLine("Your search term was not found.");
}
}
public static int LinearSearch(int[] arr, int term)
{
// set up a loop to iterate over the elements in the array
// because this is a linear search, we start at the beginning
// of the array and work through the elements looking for the term
for (var i = 0; i < arr.Length; i++)
{
// if we found a match, we can return the index in the array where the term is
if (arr[i] == term)
{
return i;
}
}
// if the term is not found, we reach the end of the array
// and as a result, we return -1 indicating that the term wasn't found
// at a valid index in the array.
return -1;
}
Binary Search
只能对有序列表使用 Binary Search。
The logic behind this search goes something like this:
Get the list to search
Find the mid-point and get an index to mark that mid-point
Compare the value at the mid-point and the search term
If the two match, the search is done. If not, proceed to the next step
Is the term greater or less than the mid-point value?
if greater, get index for mid-point between current mid-point and end of list. Repeat steps 3 to 5 and i. or ii. until term is found or not
if less than, get the index for mid-point between current mid-point and beginning of list. Repeat steps 3 to 5 and i. or ii. until term is found or not
If term is found above, end and return index of term
If term is not found above, end and return search failed result
static void BinarySearchDemo()
{
// declare an array of integers that will be used for searching
int[] arrLinearSearch = { 2, 3, 4, 5, 8, 10 };
var searchTerm = 8;
var result = BinarySearch(arrLinearSearch, searchTerm, 0, arrLinearSearch.Length - 1);
if (result != -1)
{
Console.WriteLine($"Search term found at index {result}.");
}
else
{
Console.WriteLine("Search term not found in the array.");
}
}
public static int BinarySearch(int[] arr, int key, int left, int right)
{
while (left <= right)
{
var mid = (left + right) / 2;
if (key == arr[mid])return mid;
if (key < arr[mid])
{
right = mid - 1;
}
else
{
left = mid + 1;
}
}
return -1;
}