Professional Documents
Culture Documents
Lab 3
Lab 3
Lab 3
• Compares the searching element s with each and every element of the
array/List (data structure), if the searching element s found in list A then it
returns the location of the searching element from the list of elements,
otherwise it returns the -1 – sequential search.
• Linear search is mostly used if the array contains an unordered list of
elements.
• For ex: int A [] = {10, 12, 23, 75, 3, 4, 9, 1, 8, 5, 14, 34, 56, 76, 31, 26};
searching element s = 8.
• s is found at position 9.
Step 1 – Let i := 0
Step 2: Compare the searching element s with the ith element in list A.
Step 3 - If both are matched, then return i+1.
Step 4 - If both are not matched, then increment i. If i is less than n and
then repeat the steps 2 and 3.
Step 5 - Return -1. // Element not found
ine e x mple
ist o e ements
s
1. Binary Search
The input for the Binary search is the sorted elements (pre constraint).
Idea - Compare the searching element with the middle element in the list. There
are three possibilities
1. If the middle element is greater than the searching element then the
searching element may be found only in the first half of the elements
(Searching array size reduced to half).
2. If the middle element is less than the searching element then the
searching element may be found only in the second half of the
elements (Searching array size reduced to half)
3. If the middle element matches with the searching element, then
return the position of the middle element.
• The above three steps are repeated until it matches or elements exhausted.
Algorithm:
mi /
ota n m er o comparisons og
Time Complexity:
T(n) = T(n/2) + 1 // After one comparison, the size of the problem reduced to n/2
Idea: Initialize the sum to zero. Access each element from the array and extract
its tenth-place digit and divide it with 5, if the remainder is zero then add the
element to the sum.
Algorithm
Element_Type Sum((Element_Type a[], int n) // n is the number of elements and a[] is
the array
1. sum 0, i 0
2. whi e i < n
a. i a[i]/ % %5
i. sum = sum + a[i]
b. Increment i one
3. Return sum