线性回归学习算法c语言实现
Linear Search is basically a sequential search algorithm.
线性搜索基本上是一种顺序搜索算法 。
In this algorithm, the key element is searched in the given input array in sequential order.
在此算法中,键元素按给定顺序在给定的输入数组中搜索。
If the key element is found in the input array, it returns the element.
如果在输入数组中找到key元素,它将返回该元素。
线性搜索算法 (Linear Search Algorithm)
Linear_Search ( Array X, Value i)
Linear_Search(数组X,值i)
- Set j to 1 将j设为1
- If j > n, jump to step 7 如果j> n,则跳至步骤7
- If X[j] == i, jump to step 6 如果X [j] == i,则跳至步骤6
- Then, increment j by 1 i.e. j = j+1 然后,将j加1,即j = j + 1
- Go back to step 2 返回步骤2
- Display the element i which is found at particular index i, then jump to step 8 显示在特定索引i处找到的元素i,然后跳到步骤8
- Display element not found in the set of input elements. 在输入元素集中找不到显示元素。
- Exit/End 退出/结束
线性搜索的伪代码 (Pseudo Code for Linear Search)
procedure LINEAR_SEARCH (array, key)
for each item in the array
if match element == key
return element's index
end if
end for
end procedure
C语言中线性搜索的实现 (Implementation of Linear Search in C)
- Initially, we need to mention or accept the element to be searched from the user. 首先,我们需要提及或接受用户要搜索的元素。
- Then, we create a for loop and start searching for the element in a sequential fashion. 然后,我们创建一个for循环并开始按顺序搜索元素。
- As soon as the compiler encounters a match i.e. array[element] == key value, return the element along with its position in the array. 编译器遇到匹配项即array [element] ==键值后,立即返回元素及其在数组中的位置。
- If no values are found that match the input, it returns -1. 如果找不到与输入匹配的值,则返回-1。
#include <stdio.h>
int LINEAR_SEARCH(int inp_arr[], int size, int val)
{
for (int i = 0; i < size; i++)
if (inp_arr[i] == val)
return i;
return -1;
}
int main(void)
{
int arr[] = { 10, 20, 30, 40, 50, 100, 0 };
int key = 100;
int size = 10;
int res = LINEAR_SEARCH(arr, size, key);
if (res == -1)
printf("ELEMENT NOT FOUND!!");
else
printf("Item is present at index %d", res);
return 0;
}
Output:
输出:
Item is present at index 5
线性搜索的时间复杂度 (Time Complexity of Linear Search)
The best-case complexity is O(1) if the element is found in the first iteration of the loop.
如果在循环的第一次迭代中找到元素,则最佳情况下的复杂度为O(1) 。
The worst-case time complexity is O(n), if the search element is found at the end of the array, provided the size of the array is n.
如果在数组的末尾找到搜索元素,则最坏情况下的时间复杂度是O(n) ,前提是数组的大小为n。
结论 (Conclusion)
Thus, in this article, we have understood and implemented Linear Search Algorithm.
因此,在本文中,我们已经理解并实现了线性搜索算法。
翻译自: https://www.journaldev.com/35170/linear-search-algorithm-c
线性回归学习算法c语言实现