SlideShare a Scribd company logo
1 of 24
Download to read offline
Searching
Algorithms
Searching
Objective : To find out the location of any given element in an array. If element found then
search is successful, otherwise search is unsuccessful.
Two approaches –
1. Linear Search (Sequential Search): if array elements are in random order
2. Binary Search: if array elements are in sorted order
Linear Search
Algorithm Linear_Search(a,n, Item): Let a be a given array and no. of elements is n. Pos is
representing the position of desired element Item in array a, if element found, otherwise set
Pos to -1. Variable i is used as loop variable.
1. Initialize Pos = -1
2. For i = 0 to n-1
3. If a[i] == Item
4. Set Pos = i
5. Break //break the loop
6. If Pos < 0
7. Print “Element is not found”
8. Else Print Pos
C1
C2
C3
C4
C5
C6
C7
C8
Analysis of Linear Search
Best case: When searched Item is present as the first position
Time Complexity function=C1 + C2 + C3 + C4 + C5+C6+C8
=7
Best case time Complexity = O(1)
Worst case:
i. When searched Item present at the last position
Time Complexity function=C1 + n*C2 + n * C3 + C4 + C5+C6+C8
=2n + 5= O(n)
ii. When searched Item is not present
Time Complexity function=C1+ (n+1)*C2 + n * C3 +C6+C7 = 2n + 4 =O(n)
Binary Search
Best searching approach
Constraint:
▪ Given array should be in sorted order
OR
▪ First sort the given array and then perform search, but then sorting time will be
added
1. Initialize low =0, high = n-1
2. While low <= high
3. mid = (low+high)/2
4. If a[mid] == Item
5. Set Pos = mid
6. Break and Jump to step 10
7. Else if Item < a[mid]
8. high = mid -1
9. Else low =mid +1
10. If Pos < 0
11. Print “Element is not found”
12. Else Print Pos
Binary Search (Iterative)
Algorithm Binary_Search(a,n, Item): Let a be a given array which is sorted in ascending
order and no. of elements is n. Pos is representing the position of desired element Item in
array a, if element found; otherwise, set Pos to -1. Variable mid is used to keep the mid index
of array.
Binary Search Illustration
mid = (low+high)/2
= (0 + 9) /2 = 4
item to be searched, Item = 94
0 1 2 3 4 5 6 7 8 9
If a[mid]<Item
low = mid + 1
7 8 15 27 31 57 68 94 103 104
low = 0 high = 9
mid = 4
Binary Search Illustration
mid = (low+high)/2
= (5 + 9) /2 = 7
item to be searched, Item = 94
0 1 2 3 4 5 6 7 8 9
If a[mid]==Item
Pos = mid
7 8 15 27 31 57 68 94 103 104
low = 5 high = 9
mid = 7
1. Initialize low =0, high = n-1
2. While low <= high
3. mid = (low+high)/2
4. If a[mid] == Item
5. Set Pos = mid
6. Break and Jump to step 10
7. Else if Item < a[mid]
8. high = mid -1
9. Else low =mid +1
10. If Pos < 0
11. Print “Element is not found”
12. Else Print Pos
Binary Search (Iterative)
C1
C2
C3
C4
C5
C6
C7
C8
C9
C10
C11
C12
Analysis of Iterative Binary Search
DISTINCT & SORTED ELEMENTS:
On successful search
Time Complexity =
= C1 + ( log2
n )*C2 + log2
n * (C3 + C4 +C7 +C8 +C9) + C5 + C6 +C10 +C12
= 6 log2
n + 5
= O (log2
n)
Unsuccessful search
Time Complexity = C1 + ( log2
n +1)*C2 + log2
n * (C3 + C4 +C7 +C8 +C9) +C10 + C11
= 6 log2
n + 4
= O (log2
n)
That means in worst case of a binary search, at most log2
n number of comparisons are
required to find out the desired element location which is better than the linear search.
What is the Best Case: When searched element is found as middle element;
then O(1) time is required
1. If low<=high
2. mid = (low+high)/2
3. If a[mid] == Item
4. Return mid
5. Else if Item < a[mid]
6. Return Bin_Search(a,Item,low,mid-1)
7. Else Return Bin_Search(a,Item,mid+1,high)
8. Return -1
Binary Search (Recursive)
Algorithm Bin_Search(a, Item,low, high): Let a is given array which is sorted in ascending
order and no. of elements is n. Variable mid is used to keep the mid index of array. Here,
initially low and high are assigned the lowest and highest index of array a.
Time complexity analysis of an algorithm
Algorithm
Iterative Recursive
T(n) = Total step count T(n) = Recurrence relation
Time complexity
Recurrence Relation (Cont…)
Recurrence relation is an equation that describes a function in terms of its values on smaller
inputs.
Examples :
1.
2.
3.
T(n) =
1 for n=0
T(n-1) + n n>0
T(n) =
1 for n=0
T(n/2) + 1 n>0
T(n) =
0 for n=0
1 n=1
2T(n-1) +1 n>1
Recurrence Relation (Cont…)
Recurrence relation must include two equations:
i. Equation for the general case
ii. Equation for the base case
The base case is often a O(1) operation,
In some recurrence relations the base case involves input of size one, hence base case is
like T(1) = O(1).
However, there are cases where the base case has size zero. In such cases the base case
could be T(0) = O(1).
T(n) = 2 T(n/2) + O(n) // recursive case
T(1) = O(1) // Base Case
We'll write n instead of O(n) in the first line because it makes the algebra much simpler.
T(n) = 2 T(n/2) + n
= 2 [2 T(n/4) + n/2] + n
= 4 T(n/4) + 2n
= 4 [2 T(n/8) + n/4] + 2n
= 8 T(n/8) + 3n
=16 T(n/16) + 4n
…..
…..
= 2k
T(n/2k
) + k n
We know that T(1) = 1 and this is a way to end the derivation above.
In particular we want T(1) to appear on the right hand side of the = sign.
This means we want:
n/2k
= 1 OR n = 2k
OR log2
n = k
Continuing with the previous derivation we get the following since k = log2
n:
= 2k
T(n/2k
) + k n
= 2log
2
n
T(1) + (log2
n) n = n + n log2
n
= O(n log n)
Recurrence relation by backward substitution method
Illustration 1: Factorial Recursive
Algorithm Fact_Rec(n): Let n is number for which factorial is to be calculated.
1. If n==1
2. Return 1
3. Return Fact_Rec(n-1) * n
C1
C2
C3
Therefore,
Now,
How to solve this recurrence relation ?
T(n) =
1 for n=1
T(n-1) + 1 n>1
Solving Recurrence Relation
Backward Substitution method –
T(1) = 1
T(n) = T(n -1) + 1
T(n) = T(n -1) + 1 //T(n - 1) = T(n - 2) + 1
= T(n - 2) + 1 + 1
= T(n - 2) + 2 //T(n - 2) = T(n - 3) + 1
= T(n - 3) + 1 + 2
= T(n - 3) + 3 //T(n - 3) = T(n - 4) + 1
= T(n - 4) + 4
= : : :
= T(n - k) + k
If we set n-k=1=> k=n-1 we have:
T(n) = T(1) + n-1
= 1+n-1
T(n)= n
Hence, Time complexity = O(n)
Illustration 2: Fibonacci Recursive
Algorithm Fibo_Rec(n): Let n be a number means nth
is to be calculated.
1. If n==1
2. Return 0
3. If n==2
4. Return 1
5. Return Fibo_Rec(n-1) + Fibo_Rec(n-2)
C1
C2
C3
Therefore,
T(n) =
0 for n=1
1 n=2
T(n-1) + T(n-2) +1 n>2
Solving Recurrence Relation
This is a case of deep recursion where the function makes more than one calls to
itself.
In case of a deep recursion, the time complexity would be exponential.
It grows like exponential tree.
Time complexity = O(2n
)
Analysis of Recursive Binary Search
Recurrence relation –
T(n) = T(n/2) + 1
= T(n/2*2) + 1 + 1
= T(n/2*2*2) + 3
= T(n/24
) + 4
…………….
= T(n/2k
) + k
Let n/2k
= 1, n = 2k
, log2
n = k * log2
2
i.e. k = log2
n
Now,
T(n) = T(1) + log2
n = 1 + log2
n
= O(log2
n)
T(n) =
1 for n=1
T(|_n/2_|) + 1 n>1
Recurrence Relations to Remember
Find the time complexity of the below function.
void function(int n)
{
if(n <= 1)
return;
if (n > 1)
{
print ("*");
function(n/2);
function(n/2);
}
}
T(n)=2T(n/2)+ O(1)
By solving above recurrence relation using backward substitution method, we get
Time complexity =O(n)
Find the time complexity of the below function.
function(int n)
{
if (n <= 1)
return;
for (i=1 ; i <= 3 ; i++ )
function (n − 1).
}
T(n)=3T(n-1)+O(1)
By solving above recurrence relation by backward substitution method, we
get
Time complexity =O(3n
)
Find the time complexity of the below function.
function(int n)
{
if ( n < 2 )
return;
else
counter = 0;
for i = 1 to 8 do
function (n/2);
for I =1 to n3
do
counter = counter + 1;
}
T(n)=8T(n/2)+ O(n3
) + O(1)
By solving above recurrence relation, time complexity =O(n3
logn)

More Related Content

Similar to searching.pdf

Skiena algorithm 2007 lecture08 quicksort
Skiena algorithm 2007 lecture08 quicksortSkiena algorithm 2007 lecture08 quicksort
Skiena algorithm 2007 lecture08 quicksortzukun
 
Binary Search Algorithm.pptx
Binary Search Algorithm.pptxBinary Search Algorithm.pptx
Binary Search Algorithm.pptxBhagyashreeMadan1
 
searching in data structure.pptx
searching in data structure.pptxsearching in data structure.pptx
searching in data structure.pptxchouguleamruta24
 
Skiena algorithm 2007 lecture09 linear sorting
Skiena algorithm 2007 lecture09 linear sortingSkiena algorithm 2007 lecture09 linear sorting
Skiena algorithm 2007 lecture09 linear sortingzukun
 
Algorithm, Pseudocode and Flowcharting in C++
Algorithm, Pseudocode and Flowcharting in C++Algorithm, Pseudocode and Flowcharting in C++
Algorithm, Pseudocode and Flowcharting in C++Johnny Jean Tigas
 
Quicksort analysis
Quicksort analysisQuicksort analysis
Quicksort analysisPremjeet Roy
 
Skiena algorithm 2007 lecture07 heapsort priority queues
Skiena algorithm 2007 lecture07 heapsort priority queuesSkiena algorithm 2007 lecture07 heapsort priority queues
Skiena algorithm 2007 lecture07 heapsort priority queueszukun
 
pradeepbishtLecture13 div conq
pradeepbishtLecture13 div conqpradeepbishtLecture13 div conq
pradeepbishtLecture13 div conqPradeep Bisht
 
Data structure using c module 1
Data structure using c module 1Data structure using c module 1
Data structure using c module 1smruti sarangi
 
module2_dIVIDEncONQUER_2022.pdf
module2_dIVIDEncONQUER_2022.pdfmodule2_dIVIDEncONQUER_2022.pdf
module2_dIVIDEncONQUER_2022.pdfShiwani Gupta
 

Similar to searching.pdf (20)

Skiena algorithm 2007 lecture08 quicksort
Skiena algorithm 2007 lecture08 quicksortSkiena algorithm 2007 lecture08 quicksort
Skiena algorithm 2007 lecture08 quicksort
 
Binary Search Algorithm.pptx
Binary Search Algorithm.pptxBinary Search Algorithm.pptx
Binary Search Algorithm.pptx
 
search_sort.ppt
search_sort.pptsearch_sort.ppt
search_sort.ppt
 
searching in data structure.pptx
searching in data structure.pptxsearching in data structure.pptx
searching in data structure.pptx
 
Unit 2 in daa
Unit 2 in daaUnit 2 in daa
Unit 2 in daa
 
algorithm Unit 2
algorithm Unit 2 algorithm Unit 2
algorithm Unit 2
 
21-algorithms.ppt
21-algorithms.ppt21-algorithms.ppt
21-algorithms.ppt
 
2.pptx
2.pptx2.pptx
2.pptx
 
Skiena algorithm 2007 lecture09 linear sorting
Skiena algorithm 2007 lecture09 linear sortingSkiena algorithm 2007 lecture09 linear sorting
Skiena algorithm 2007 lecture09 linear sorting
 
21-algorithms.ppt
21-algorithms.ppt21-algorithms.ppt
21-algorithms.ppt
 
Algorithm, Pseudocode and Flowcharting in C++
Algorithm, Pseudocode and Flowcharting in C++Algorithm, Pseudocode and Flowcharting in C++
Algorithm, Pseudocode and Flowcharting in C++
 
arrays
arraysarrays
arrays
 
21-algorithms (1).ppt
21-algorithms (1).ppt21-algorithms (1).ppt
21-algorithms (1).ppt
 
Unit6 C
Unit6 C Unit6 C
Unit6 C
 
Quicksort analysis
Quicksort analysisQuicksort analysis
Quicksort analysis
 
Skiena algorithm 2007 lecture07 heapsort priority queues
Skiena algorithm 2007 lecture07 heapsort priority queuesSkiena algorithm 2007 lecture07 heapsort priority queues
Skiena algorithm 2007 lecture07 heapsort priority queues
 
Tower of Hanoi.ppt
Tower of Hanoi.pptTower of Hanoi.ppt
Tower of Hanoi.ppt
 
pradeepbishtLecture13 div conq
pradeepbishtLecture13 div conqpradeepbishtLecture13 div conq
pradeepbishtLecture13 div conq
 
Data structure using c module 1
Data structure using c module 1Data structure using c module 1
Data structure using c module 1
 
module2_dIVIDEncONQUER_2022.pdf
module2_dIVIDEncONQUER_2022.pdfmodule2_dIVIDEncONQUER_2022.pdf
module2_dIVIDEncONQUER_2022.pdf
 

Recently uploaded

Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxk795866
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLDeelipZope
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxKartikeyaDwivedi3
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.eptoze12
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)dollysharma2066
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...VICTOR MAESTRE RAMIREZ
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxbritheesh05
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...asadnawaz62
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx959SahilShah
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerAnamika Sarkar
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort servicejennyeacort
 

Recently uploaded (20)

Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptx
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCL
 
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptx
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptx
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
young call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Serviceyoung call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Service
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 

searching.pdf

  • 2. Searching Objective : To find out the location of any given element in an array. If element found then search is successful, otherwise search is unsuccessful. Two approaches – 1. Linear Search (Sequential Search): if array elements are in random order 2. Binary Search: if array elements are in sorted order
  • 3. Linear Search Algorithm Linear_Search(a,n, Item): Let a be a given array and no. of elements is n. Pos is representing the position of desired element Item in array a, if element found, otherwise set Pos to -1. Variable i is used as loop variable. 1. Initialize Pos = -1 2. For i = 0 to n-1 3. If a[i] == Item 4. Set Pos = i 5. Break //break the loop 6. If Pos < 0 7. Print “Element is not found” 8. Else Print Pos C1 C2 C3 C4 C5 C6 C7 C8
  • 4. Analysis of Linear Search Best case: When searched Item is present as the first position Time Complexity function=C1 + C2 + C3 + C4 + C5+C6+C8 =7 Best case time Complexity = O(1) Worst case: i. When searched Item present at the last position Time Complexity function=C1 + n*C2 + n * C3 + C4 + C5+C6+C8 =2n + 5= O(n) ii. When searched Item is not present Time Complexity function=C1+ (n+1)*C2 + n * C3 +C6+C7 = 2n + 4 =O(n)
  • 5. Binary Search Best searching approach Constraint: ▪ Given array should be in sorted order OR ▪ First sort the given array and then perform search, but then sorting time will be added
  • 6. 1. Initialize low =0, high = n-1 2. While low <= high 3. mid = (low+high)/2 4. If a[mid] == Item 5. Set Pos = mid 6. Break and Jump to step 10 7. Else if Item < a[mid] 8. high = mid -1 9. Else low =mid +1 10. If Pos < 0 11. Print “Element is not found” 12. Else Print Pos Binary Search (Iterative) Algorithm Binary_Search(a,n, Item): Let a be a given array which is sorted in ascending order and no. of elements is n. Pos is representing the position of desired element Item in array a, if element found; otherwise, set Pos to -1. Variable mid is used to keep the mid index of array.
  • 7. Binary Search Illustration mid = (low+high)/2 = (0 + 9) /2 = 4 item to be searched, Item = 94 0 1 2 3 4 5 6 7 8 9 If a[mid]<Item low = mid + 1 7 8 15 27 31 57 68 94 103 104 low = 0 high = 9 mid = 4
  • 8. Binary Search Illustration mid = (low+high)/2 = (5 + 9) /2 = 7 item to be searched, Item = 94 0 1 2 3 4 5 6 7 8 9 If a[mid]==Item Pos = mid 7 8 15 27 31 57 68 94 103 104 low = 5 high = 9 mid = 7
  • 9. 1. Initialize low =0, high = n-1 2. While low <= high 3. mid = (low+high)/2 4. If a[mid] == Item 5. Set Pos = mid 6. Break and Jump to step 10 7. Else if Item < a[mid] 8. high = mid -1 9. Else low =mid +1 10. If Pos < 0 11. Print “Element is not found” 12. Else Print Pos Binary Search (Iterative) C1 C2 C3 C4 C5 C6 C7 C8 C9 C10 C11 C12
  • 10. Analysis of Iterative Binary Search DISTINCT & SORTED ELEMENTS: On successful search Time Complexity = = C1 + ( log2 n )*C2 + log2 n * (C3 + C4 +C7 +C8 +C9) + C5 + C6 +C10 +C12 = 6 log2 n + 5 = O (log2 n) Unsuccessful search Time Complexity = C1 + ( log2 n +1)*C2 + log2 n * (C3 + C4 +C7 +C8 +C9) +C10 + C11 = 6 log2 n + 4 = O (log2 n) That means in worst case of a binary search, at most log2 n number of comparisons are required to find out the desired element location which is better than the linear search. What is the Best Case: When searched element is found as middle element; then O(1) time is required
  • 11. 1. If low<=high 2. mid = (low+high)/2 3. If a[mid] == Item 4. Return mid 5. Else if Item < a[mid] 6. Return Bin_Search(a,Item,low,mid-1) 7. Else Return Bin_Search(a,Item,mid+1,high) 8. Return -1 Binary Search (Recursive) Algorithm Bin_Search(a, Item,low, high): Let a is given array which is sorted in ascending order and no. of elements is n. Variable mid is used to keep the mid index of array. Here, initially low and high are assigned the lowest and highest index of array a.
  • 12. Time complexity analysis of an algorithm Algorithm Iterative Recursive T(n) = Total step count T(n) = Recurrence relation Time complexity
  • 13. Recurrence Relation (Cont…) Recurrence relation is an equation that describes a function in terms of its values on smaller inputs. Examples : 1. 2. 3. T(n) = 1 for n=0 T(n-1) + n n>0 T(n) = 1 for n=0 T(n/2) + 1 n>0 T(n) = 0 for n=0 1 n=1 2T(n-1) +1 n>1
  • 14. Recurrence Relation (Cont…) Recurrence relation must include two equations: i. Equation for the general case ii. Equation for the base case The base case is often a O(1) operation, In some recurrence relations the base case involves input of size one, hence base case is like T(1) = O(1). However, there are cases where the base case has size zero. In such cases the base case could be T(0) = O(1).
  • 15. T(n) = 2 T(n/2) + O(n) // recursive case T(1) = O(1) // Base Case We'll write n instead of O(n) in the first line because it makes the algebra much simpler. T(n) = 2 T(n/2) + n = 2 [2 T(n/4) + n/2] + n = 4 T(n/4) + 2n = 4 [2 T(n/8) + n/4] + 2n = 8 T(n/8) + 3n =16 T(n/16) + 4n ….. ….. = 2k T(n/2k ) + k n We know that T(1) = 1 and this is a way to end the derivation above. In particular we want T(1) to appear on the right hand side of the = sign. This means we want: n/2k = 1 OR n = 2k OR log2 n = k Continuing with the previous derivation we get the following since k = log2 n: = 2k T(n/2k ) + k n = 2log 2 n T(1) + (log2 n) n = n + n log2 n = O(n log n) Recurrence relation by backward substitution method
  • 16. Illustration 1: Factorial Recursive Algorithm Fact_Rec(n): Let n is number for which factorial is to be calculated. 1. If n==1 2. Return 1 3. Return Fact_Rec(n-1) * n C1 C2 C3 Therefore, Now, How to solve this recurrence relation ? T(n) = 1 for n=1 T(n-1) + 1 n>1
  • 17. Solving Recurrence Relation Backward Substitution method – T(1) = 1 T(n) = T(n -1) + 1 T(n) = T(n -1) + 1 //T(n - 1) = T(n - 2) + 1 = T(n - 2) + 1 + 1 = T(n - 2) + 2 //T(n - 2) = T(n - 3) + 1 = T(n - 3) + 1 + 2 = T(n - 3) + 3 //T(n - 3) = T(n - 4) + 1 = T(n - 4) + 4 = : : : = T(n - k) + k If we set n-k=1=> k=n-1 we have: T(n) = T(1) + n-1 = 1+n-1 T(n)= n Hence, Time complexity = O(n)
  • 18. Illustration 2: Fibonacci Recursive Algorithm Fibo_Rec(n): Let n be a number means nth is to be calculated. 1. If n==1 2. Return 0 3. If n==2 4. Return 1 5. Return Fibo_Rec(n-1) + Fibo_Rec(n-2) C1 C2 C3 Therefore, T(n) = 0 for n=1 1 n=2 T(n-1) + T(n-2) +1 n>2
  • 19. Solving Recurrence Relation This is a case of deep recursion where the function makes more than one calls to itself. In case of a deep recursion, the time complexity would be exponential. It grows like exponential tree. Time complexity = O(2n )
  • 20. Analysis of Recursive Binary Search Recurrence relation – T(n) = T(n/2) + 1 = T(n/2*2) + 1 + 1 = T(n/2*2*2) + 3 = T(n/24 ) + 4 ……………. = T(n/2k ) + k Let n/2k = 1, n = 2k , log2 n = k * log2 2 i.e. k = log2 n Now, T(n) = T(1) + log2 n = 1 + log2 n = O(log2 n) T(n) = 1 for n=1 T(|_n/2_|) + 1 n>1
  • 22. Find the time complexity of the below function. void function(int n) { if(n <= 1) return; if (n > 1) { print ("*"); function(n/2); function(n/2); } } T(n)=2T(n/2)+ O(1) By solving above recurrence relation using backward substitution method, we get Time complexity =O(n)
  • 23. Find the time complexity of the below function. function(int n) { if (n <= 1) return; for (i=1 ; i <= 3 ; i++ ) function (n − 1). } T(n)=3T(n-1)+O(1) By solving above recurrence relation by backward substitution method, we get Time complexity =O(3n )
  • 24. Find the time complexity of the below function. function(int n) { if ( n < 2 ) return; else counter = 0; for i = 1 to 8 do function (n/2); for I =1 to n3 do counter = counter + 1; } T(n)=8T(n/2)+ O(n3 ) + O(1) By solving above recurrence relation, time complexity =O(n3 logn)