Javatpoint Logo
Javatpoint Logo

Searching

Searching is the process of finding some particular element in the list. If the element is present in the list, then the process is called successful and the process returns the location of that element, otherwise the search is called unsuccessful.

There are two popular search methods that are widely used in order to search some item into the list. However, choice of the algorithm depends upon the arrangement of the list.

  • Linear Search
  • Binary Search

Linear Search

Linear search is the simplest search algorithm and often called sequential search. In this type of searching, we simply traverse the list completely and match each element of the list with the item whose location is to be found. If the match found then location of the item is returned otherwise the algorithm return NULL.

Linear search is mostly used to search an unordered list in which the items are not sorted. The algorithm of linear search is given as follows.

Algorithm

  • LINEAR_SEARCH(A, N, VAL)
  • Step 1: [INITIALIZE] SET POS = -1
  • Step 2: [INITIALIZE] SET I = 1
  • Step 3: Repeat Step 4 while I<=N
  • Step 4: IF A[I] = VAL
    SET POS = I
    PRINT POS
    Go to Step 6
    [END OF IF]
    SET I = I + 1
    [END OF LOOP]
  • Step 5: IF POS = -1
    PRINT " VALUE IS NOT PRESENTIN THE ARRAY "
    [END OF IF]
  • Step 6: EXIT

Complexity of algorithm

Complexity Best Case Average Case Worst Case
Time O(1) O(n) O(n)
Space O(1)

C Program

Output:

Enter Item which is to be searched
20
Item not found
Enter Item which is to be searched
23
Item found at location 2 

Java Program

Output:

Enter Item ?
23
Item found at location 2
Enter Item ?
22
Item not found

C# Program

Output:

Enter the item value
78
Item Found at Location 10

Enter the item value 
22
Item not found 

Python Program

Output:

Enter the item which you want to search 2
Item found at location 2
Enter the item which you want to search 101 
Item not found

Next TopicBinary Search




Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


B.Tech / MCA