Table of content
Searching Algorithms
- searching is the process of finding an item with specified properties from a collection of items. The items may be stored as records in a database, simple data elements in arrays or they may be elements of other search spaces.
There are certain ways of organizing the data that improves the searching process.
Classification :
Generally There are two categories of searching.
- a)Sequential Search
- b) Interval Search:
- The Example of Sequential Search is :-(Linear Search).
- The Example of Interval Search is :- (Binary Search).
Linear Search
- Start from the zero index of array and one by one compare Search Element(X) with each element of arr[].
- If Search Element(X) matches with an element of the arr[], return the index.
- If Search Element(X) doesn’t match with any of elements, then return -1.
Some More Example
Code
// C++ code to linearly search x in arr[]. If search ELement (x)
// is present then return its Index, otherwise
// return -1
#include <iostream>
using namespace std;
int search(int arr[], int n, int searchkey)
{
for (int i = 0; i < n; i++)
if (arr[i] == searchkey)
return i;
return -1;
}
// Driver code
int main()
{
int arr[] = { 2, 3, 4, 10, 40 };
int searchkey; // = 10;
cin>> searchkey;
int n = sizeof(arr) / sizeof(arr[0]);
// Function call
int result = search(arr, n, searchkey);
(result == -1)
? cout << "Element is not present in array"
: cout << "Element is present at index " << result;
return 0;
}
Properties
- Time Complexity : O(n)
- Space Complexity : O(1)
- It has a very simple implementation.
Advantages
- The list does not need to sorted
Disadvantage
- Inversely, slow searching of big lists.