SlideShare a Scribd company logo
1 of 17
SEARCHING
• SEARCHING REFERS TO THE
OPERATION OF FINDING THE
LOCATION OF A GIVEN SEARCH
ITEM IN THE GIVEN COLLECTION
OF ITEMS.
Linear Search or Sequential search
THE MOST STRAIGHT FORWARD METHOD OF FINDING A PARTICULAR ELEMENT IN AN
UNORDERED LIST IS LINEAR SEARCH. THIS TECHNIQUE SIMPLY INVOLVES THE COMPARISON
OF EACH ELEMENT OF THE LIST IN A SEQUENTIAL MANNER UNTIL THE DESIRED ELEMENT IS
FOUND.
ALGORITHM: LINEAR SEARCH
A IS AN ARRAY WITH N ELEMENTS AND SEARCHITEM IS THE ELEMENT TO BE SEARCHED FOR.
STEP1:LOC=-1
STEP 2:FOR I=0 TO N-1 DO
STEP 3:IF(SEARCHITEM = = A[I])THEN
LOC=I
GOTO STEP 6
ENDIF
END OF FOR LOOP
STEP 6: IF(LOC>=0)THEN
DISPLAY ”SEARCHITEM FOUND AT POSITION (LOC+1)”
ELSE
DISPLAY “SEARCHITEM NOT FOUND”
ENDIF
STEP 7:EXIT
Example:
CASE I: ELEMENT FOUND IN THE LIST
CONSIDER THE ELEMENTS 22 11 66 44 WHERE N=4 AND THE SEARCHITEM=66
I=0 ,LOC = -1
A[I]=22
22 != 66 INCREMNT I, AND I=1
A[I]=11
11!= 66 INCREMNT I, AND I=2
A[2] = =66
LOC=2
THEREFORE 66 IS FOUND IN POSITION 3 (LOC+1)
CASE II: ELEMENT NOT FOUND IN THE LIST
CONSIDER THE SEARCH ITEM 99 IN THE ABOVE LIST 22 11 66 44
I=0 ,LOC= -1
A[I]=22
22 != 99 INCREMNT I, AND I=1
A[I]=11
11!= 99 INCREMNT I, AND I=2
A[2] =66
66!=99 INCREMNT I, AND I=3
A[3] =44
/*Program to perform Linear Search using iteration*/
#include<stdio.h>
int linear(int[],int,int);
void main()
{
int i,key,a[20],n,loc=-1;
clrscr();
printf("Enter the number of elementsn");
scanf("%d",&n);
printf("Enter the elementsn");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter the search elementn");
scanf("%d",&key);
loc=linear(a,n,key);
if(loc>=0)
printf("Element found at %d positionn",loc+1);
else
printf("Element not foundn");
getch();
}
/*Program to perform Linear Search using iteration*/
#include<stdio.h>
int linear(int[],int,int);
void main()
{
int i,key,a[20],n,loc=-1;
clrscr();
printf("Enter the number of elementsn");
scanf("%d",&n);
printf("Enter the elementsn");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter the search elementn");
scanf("%d",&key);
loc=linear(a,n,key);
if(loc>=0)
printf("Element found at %d positionn",loc+1);
else
printf("Element not foundn");
getch();
}
/*Program to perform Linear Search using iteration*/
/*Linear search iterative function*/
int linear(int a[10],int n,int search)
{
int i;
for(i=0;i<n;i++)
{
if(a[i]==search)
return(i);
}
return(-1);
}
/*Program to perform Linear Search using iteration*/
/*Linear search iterative function*/
int linear(int a[10],int n,int search)
{
int i;
for(i=0;i<n;i++)
{
if(a[i]==search)
return(i);
}
return(-1);
}
/*Program to perform Linear Search using iteration*/
Output:
Enter the number of elements
3
Enter the elements
33 21 19
Enter the search element
21
Element found at 2 position
/*Program to perform Linear Search using recursion*/
#include<stdio.h>
int linear(int[],int,int);
void main()
{
int i,key,a[20],n,loc=-1;
clrscr();
printf("Enter the number of elementsn");
scanf("%d",&n);
printf("enter the elementsn");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter the search elementn");
scanf("%d",&key);
loc=linear(a,n,key);
if(loc>=0)
printf("Element found at %d positionn",loc+1);
else
printf("Element not foundn");
getch();
}
/*Linear search recursive function*/
int linear(int a[10],int n,int search)
{
if(n<0)
return(-1);
else
if(a[n-1]==search)
return(n-1);
else
return(linear(a,n-1,search));
}
Complexity of linear search
The complexity of the algorithm is measured by the number of comparisons f(n)
required to find the search element ITEM in the array A consisting of n elements. The worst
case occurs when we search through the entire array A and ITEM does not appear in A.
In this case algorithm requires
f(n)= n+1 comparisons
Thus in the worst case f(n) is proportional to n
The number of comparisons in the average case can be any number 1,2,…. N and
each number occurs with probability P=1/n. then
f (n) = 1.1/n + 2.1/n + ….. n. 1/n
= (1+2+……n). 1/n
= n(n+1)/2. 1/n
= (n+1)/2
Hence f(n) in the average case is approximately equal to half the number of elements in the
list.
In the best case the element can be found in the first comparison itself where f(n)=1.
Binary Search:
An element can be found in an ordered list by using Binary
search. In this the search element is compared with the
middle element in the list. If the search element is lesser than
the middle element the binary search is performed again only
on the elements to the left of the middle element. If the
search element is greater than the middle element then the
search is made to the right of middle element. This process
continues until the desired element is found or the search list
becomes empty.
Algorithm: Binary Search
A is a sorted array with n elements and searchitem is the element to be searched for in the list.
low and high is used to identify the first and last elements in the range and mid gives the
position of middle element.
Step1: Initialize the variables
low=0, high=n-1,LOC=-1
Step2: while(low<= high)do
mid=(low+high)/2
Step 3: if(searchitem = = A[mid])
LOC=mid
GOTO Step 6
Endif
Step 4:if(searchitem<A[mid])then
high=mid-1
Step 5:else
low=mid+1
Endif
End of while loop
Step 6:if(LOC>=0)then
Display ”searchitem found at position (LOC+1)”
else
Display “searchitem not found”
Endif
Step 7:Exit
Example:
Consider the elements in array A
11 22 33 44 where n=4
and search element ITEM is 11
low = 0(lower bound)
high = 3(upper bound)
mid = (0+3)/2 =1
ITEM<A[mid] so go to the lower half segment.
Therefore reset the value of high to mid-1
low=0 high=0
mid=0
ITEM= =A[0] and search element 11 is found at position 1 (mid+1).
Consider the search element 77 in the above list 11 22 33 44
low = 0(lower bound)
high = 3(upper bound)
mid = (0+3)/2 =1
A[mid]=22
ITEM>A[mid] so go to the upper half segment.
Therefore reset the value of low to mid+1
low=2 high=3
mid=2
A[mid]=33
ITEM>A[mid] so go to the upper half segment.
Therefore reset the value of low to mid+1
low=3 high=3
mid=3
a[mid]=44
ITEM>A[mid] so go to the upper half segment.
Therefore reset the value of low to mid+1
low=4
Now low>high and therefore conclude that the element is not found in the list.
/*Program to perform Binary Search using iteration*/
#include<stdio.h>
int binary(int[],int,int,int);
void main()
{
int i,key,a[20],n,loc=-1;
clrscr();
printf("Enter the number of elementsn");
scanf("%d",&n);
printf("enter the elementsn");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter the search elementn");
scanf("%d",&key);
loc=binary(a,0,n-1,key);
if(loc>=0)
printf("Element found at %d positionn",loc+1);
else
printf("Element not foundn");
getch(); }
/*Binary search iterative function*/
int binary(int a[10],int low,int high,int item)
{
int mid;
while(low<=high)
{
mid=(low+high)/2;
if(item==a[mid])
return(mid);
else if(item>a[mid])
low=mid+1;
else if(item<a[mid])
high=mid-1;
}
return(-1);
Thank
you!

More Related Content

What's hot (20)

presentation-225new
presentation-225newpresentation-225new
presentation-225new
 
Program listds
Program listdsProgram listds
Program listds
 
D404 ex-4-2
D404 ex-4-2D404 ex-4-2
D404 ex-4-2
 
Address calculation-sort
Address calculation-sortAddress calculation-sort
Address calculation-sort
 
1. 2 Singly Linked List
1. 2 Singly Linked List1. 2 Singly Linked List
1. 2 Singly Linked List
 
Skip lists (Advance Data structure)
Skip lists (Advance Data structure)Skip lists (Advance Data structure)
Skip lists (Advance Data structure)
 
366 it elective 4 (analysis of algoritm)
366 it elective 4 (analysis of algoritm)366 it elective 4 (analysis of algoritm)
366 it elective 4 (analysis of algoritm)
 
STACK ( LIFO STRUCTURE) - Data Structure
STACK ( LIFO STRUCTURE) - Data StructureSTACK ( LIFO STRUCTURE) - Data Structure
STACK ( LIFO STRUCTURE) - Data Structure
 
2.1 STACK & QUEUE ADTS
2.1 STACK & QUEUE ADTS2.1 STACK & QUEUE ADTS
2.1 STACK & QUEUE ADTS
 
Stack
StackStack
Stack
 
Dictionary and sets-converted
Dictionary and sets-convertedDictionary and sets-converted
Dictionary and sets-converted
 
DSA UNIT II ARRAY AND LIST - notes
DSA UNIT II ARRAY AND LIST - notesDSA UNIT II ARRAY AND LIST - notes
DSA UNIT II ARRAY AND LIST - notes
 
List interface
List interfaceList interface
List interface
 
Quiz2 cs141-1-17
Quiz2 cs141-1-17Quiz2 cs141-1-17
Quiz2 cs141-1-17
 
Stack of Data structure
Stack of Data structureStack of Data structure
Stack of Data structure
 
(Data Structure) Chapter11 searching & sorting
(Data Structure) Chapter11 searching & sorting(Data Structure) Chapter11 searching & sorting
(Data Structure) Chapter11 searching & sorting
 
Linked lists
Linked listsLinked lists
Linked lists
 
DSA- Unit III- STACK AND QUEUE
DSA- Unit III- STACK AND QUEUEDSA- Unit III- STACK AND QUEUE
DSA- Unit III- STACK AND QUEUE
 
Basic Sorting algorithms csharp
Basic Sorting algorithms csharpBasic Sorting algorithms csharp
Basic Sorting algorithms csharp
 
Python programming
Python programmingPython programming
Python programming
 

Similar to Linear and binary search

Similar to Linear and binary search (20)

Searching linear &amp; binary search
Searching linear &amp; binary searchSearching linear &amp; binary search
Searching linear &amp; binary search
 
Searching
Searching Searching
Searching
 
Searching_Sorting.pptx
Searching_Sorting.pptxSearching_Sorting.pptx
Searching_Sorting.pptx
 
searching in data structure.pptx
searching in data structure.pptxsearching in data structure.pptx
searching in data structure.pptx
 
Unit 6 dsa SEARCHING AND SORTING
Unit 6 dsa SEARCHING AND SORTINGUnit 6 dsa SEARCHING AND SORTING
Unit 6 dsa SEARCHING AND SORTING
 
Searching
SearchingSearching
Searching
 
searching
searchingsearching
searching
 
search_sort.ppt
search_sort.pptsearch_sort.ppt
search_sort.ppt
 
Searching in c language
Searching in c languageSearching in c language
Searching in c language
 
DSA Lec 5+6(Search+Sort) (1).pdf
DSA Lec 5+6(Search+Sort) (1).pdfDSA Lec 5+6(Search+Sort) (1).pdf
DSA Lec 5+6(Search+Sort) (1).pdf
 
seaching internal 2 ppt.pptx
seaching internal 2 ppt.pptxseaching internal 2 ppt.pptx
seaching internal 2 ppt.pptx
 
Linear and Binary search .pptx
Linear and Binary search .pptxLinear and Binary search .pptx
Linear and Binary search .pptx
 
Searching and sorting by B kirron Reddi
Searching and sorting by B kirron ReddiSearching and sorting by B kirron Reddi
Searching and sorting by B kirron Reddi
 
21-algorithms.ppt
21-algorithms.ppt21-algorithms.ppt
21-algorithms.ppt
 
MODULE 5-Searching and-sorting
MODULE 5-Searching and-sortingMODULE 5-Searching and-sorting
MODULE 5-Searching and-sorting
 
sorting and searching.pptx
sorting and searching.pptxsorting and searching.pptx
sorting and searching.pptx
 
21-algorithms (1).ppt
21-algorithms (1).ppt21-algorithms (1).ppt
21-algorithms (1).ppt
 
Searching in DSA that follow a dsa searching.pptx
Searching in DSA that follow a dsa searching.pptxSearching in DSA that follow a dsa searching.pptx
Searching in DSA that follow a dsa searching.pptx
 
advanced searching and sorting.pdf
advanced searching and sorting.pdfadvanced searching and sorting.pdf
advanced searching and sorting.pdf
 
Dsa – data structure and algorithms searching
Dsa – data structure and algorithms   searchingDsa – data structure and algorithms   searching
Dsa – data structure and algorithms searching
 

More from JeoJoyA

Tree (1).pptx
Tree (1).pptxTree (1).pptx
Tree (1).pptxJeoJoyA
 
Sutherland Hodgman Polygon Clipping Technique.pptx
Sutherland Hodgman Polygon Clipping Technique.pptxSutherland Hodgman Polygon Clipping Technique.pptx
Sutherland Hodgman Polygon Clipping Technique.pptxJeoJoyA
 
Visible Surfacte Detection Methods - Z-Buffer and Scanline methods.pptx
Visible Surfacte Detection Methods - Z-Buffer and Scanline methods.pptxVisible Surfacte Detection Methods - Z-Buffer and Scanline methods.pptx
Visible Surfacte Detection Methods - Z-Buffer and Scanline methods.pptxJeoJoyA
 
Segment Structure Display List in Computer Graphics.pptx
Segment Structure Display List in Computer Graphics.pptxSegment Structure Display List in Computer Graphics.pptx
Segment Structure Display List in Computer Graphics.pptxJeoJoyA
 
Recursion Merge Sort Quick Sort.pptx
Recursion Merge Sort Quick Sort.pptxRecursion Merge Sort Quick Sort.pptx
Recursion Merge Sort Quick Sort.pptxJeoJoyA
 
Linear Search Swapping Bubble Sort Binary Search.pptx
Linear Search Swapping Bubble Sort Binary Search.pptxLinear Search Swapping Bubble Sort Binary Search.pptx
Linear Search Swapping Bubble Sort Binary Search.pptxJeoJoyA
 
Tree.pptx
Tree.pptxTree.pptx
Tree.pptxJeoJoyA
 
Linked list
Linked listLinked list
Linked listJeoJoyA
 

More from JeoJoyA (10)

Tree (1).pptx
Tree (1).pptxTree (1).pptx
Tree (1).pptx
 
OpenGL
OpenGLOpenGL
OpenGL
 
Sutherland Hodgman Polygon Clipping Technique.pptx
Sutherland Hodgman Polygon Clipping Technique.pptxSutherland Hodgman Polygon Clipping Technique.pptx
Sutherland Hodgman Polygon Clipping Technique.pptx
 
Visible Surfacte Detection Methods - Z-Buffer and Scanline methods.pptx
Visible Surfacte Detection Methods - Z-Buffer and Scanline methods.pptxVisible Surfacte Detection Methods - Z-Buffer and Scanline methods.pptx
Visible Surfacte Detection Methods - Z-Buffer and Scanline methods.pptx
 
Segment Structure Display List in Computer Graphics.pptx
Segment Structure Display List in Computer Graphics.pptxSegment Structure Display List in Computer Graphics.pptx
Segment Structure Display List in Computer Graphics.pptx
 
Recursion Merge Sort Quick Sort.pptx
Recursion Merge Sort Quick Sort.pptxRecursion Merge Sort Quick Sort.pptx
Recursion Merge Sort Quick Sort.pptx
 
Linear Search Swapping Bubble Sort Binary Search.pptx
Linear Search Swapping Bubble Sort Binary Search.pptxLinear Search Swapping Bubble Sort Binary Search.pptx
Linear Search Swapping Bubble Sort Binary Search.pptx
 
Tree.pptx
Tree.pptxTree.pptx
Tree.pptx
 
Linked list
Linked listLinked list
Linked list
 
Tree
TreeTree
Tree
 

Recently uploaded

Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxUnboundStockton
 
Science lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lessonScience lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lessonJericReyAuditor
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxsocialsciencegdgrohi
 
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxAnaBeatriceAblay2
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerunnathinaik
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 

Recently uploaded (20)

Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docx
 
Science lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lessonScience lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lesson
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
 
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developer
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 

Linear and binary search

  • 1. SEARCHING • SEARCHING REFERS TO THE OPERATION OF FINDING THE LOCATION OF A GIVEN SEARCH ITEM IN THE GIVEN COLLECTION OF ITEMS.
  • 2. Linear Search or Sequential search THE MOST STRAIGHT FORWARD METHOD OF FINDING A PARTICULAR ELEMENT IN AN UNORDERED LIST IS LINEAR SEARCH. THIS TECHNIQUE SIMPLY INVOLVES THE COMPARISON OF EACH ELEMENT OF THE LIST IN A SEQUENTIAL MANNER UNTIL THE DESIRED ELEMENT IS FOUND. ALGORITHM: LINEAR SEARCH A IS AN ARRAY WITH N ELEMENTS AND SEARCHITEM IS THE ELEMENT TO BE SEARCHED FOR. STEP1:LOC=-1 STEP 2:FOR I=0 TO N-1 DO STEP 3:IF(SEARCHITEM = = A[I])THEN LOC=I GOTO STEP 6 ENDIF END OF FOR LOOP STEP 6: IF(LOC>=0)THEN DISPLAY ”SEARCHITEM FOUND AT POSITION (LOC+1)” ELSE DISPLAY “SEARCHITEM NOT FOUND” ENDIF STEP 7:EXIT
  • 3. Example: CASE I: ELEMENT FOUND IN THE LIST CONSIDER THE ELEMENTS 22 11 66 44 WHERE N=4 AND THE SEARCHITEM=66 I=0 ,LOC = -1 A[I]=22 22 != 66 INCREMNT I, AND I=1 A[I]=11 11!= 66 INCREMNT I, AND I=2 A[2] = =66 LOC=2 THEREFORE 66 IS FOUND IN POSITION 3 (LOC+1) CASE II: ELEMENT NOT FOUND IN THE LIST CONSIDER THE SEARCH ITEM 99 IN THE ABOVE LIST 22 11 66 44 I=0 ,LOC= -1 A[I]=22 22 != 99 INCREMNT I, AND I=1 A[I]=11 11!= 99 INCREMNT I, AND I=2 A[2] =66 66!=99 INCREMNT I, AND I=3 A[3] =44
  • 4. /*Program to perform Linear Search using iteration*/ #include<stdio.h> int linear(int[],int,int); void main() { int i,key,a[20],n,loc=-1; clrscr(); printf("Enter the number of elementsn"); scanf("%d",&n); printf("Enter the elementsn"); for(i=0;i<n;i++) scanf("%d",&a[i]); printf("Enter the search elementn"); scanf("%d",&key); loc=linear(a,n,key); if(loc>=0) printf("Element found at %d positionn",loc+1); else printf("Element not foundn"); getch(); }
  • 5. /*Program to perform Linear Search using iteration*/ #include<stdio.h> int linear(int[],int,int); void main() { int i,key,a[20],n,loc=-1; clrscr(); printf("Enter the number of elementsn"); scanf("%d",&n); printf("Enter the elementsn"); for(i=0;i<n;i++) scanf("%d",&a[i]); printf("Enter the search elementn"); scanf("%d",&key); loc=linear(a,n,key); if(loc>=0) printf("Element found at %d positionn",loc+1); else printf("Element not foundn"); getch(); }
  • 6. /*Program to perform Linear Search using iteration*/ /*Linear search iterative function*/ int linear(int a[10],int n,int search) { int i; for(i=0;i<n;i++) { if(a[i]==search) return(i); } return(-1); }
  • 7. /*Program to perform Linear Search using iteration*/ /*Linear search iterative function*/ int linear(int a[10],int n,int search) { int i; for(i=0;i<n;i++) { if(a[i]==search) return(i); } return(-1); }
  • 8. /*Program to perform Linear Search using iteration*/ Output: Enter the number of elements 3 Enter the elements 33 21 19 Enter the search element 21 Element found at 2 position
  • 9. /*Program to perform Linear Search using recursion*/ #include<stdio.h> int linear(int[],int,int); void main() { int i,key,a[20],n,loc=-1; clrscr(); printf("Enter the number of elementsn"); scanf("%d",&n); printf("enter the elementsn"); for(i=0;i<n;i++) scanf("%d",&a[i]); printf("Enter the search elementn"); scanf("%d",&key); loc=linear(a,n,key); if(loc>=0) printf("Element found at %d positionn",loc+1); else printf("Element not foundn"); getch(); }
  • 10. /*Linear search recursive function*/ int linear(int a[10],int n,int search) { if(n<0) return(-1); else if(a[n-1]==search) return(n-1); else return(linear(a,n-1,search)); }
  • 11. Complexity of linear search The complexity of the algorithm is measured by the number of comparisons f(n) required to find the search element ITEM in the array A consisting of n elements. The worst case occurs when we search through the entire array A and ITEM does not appear in A. In this case algorithm requires f(n)= n+1 comparisons Thus in the worst case f(n) is proportional to n The number of comparisons in the average case can be any number 1,2,…. N and each number occurs with probability P=1/n. then f (n) = 1.1/n + 2.1/n + ….. n. 1/n = (1+2+……n). 1/n = n(n+1)/2. 1/n = (n+1)/2 Hence f(n) in the average case is approximately equal to half the number of elements in the list. In the best case the element can be found in the first comparison itself where f(n)=1.
  • 12. Binary Search: An element can be found in an ordered list by using Binary search. In this the search element is compared with the middle element in the list. If the search element is lesser than the middle element the binary search is performed again only on the elements to the left of the middle element. If the search element is greater than the middle element then the search is made to the right of middle element. This process continues until the desired element is found or the search list becomes empty.
  • 13. Algorithm: Binary Search A is a sorted array with n elements and searchitem is the element to be searched for in the list. low and high is used to identify the first and last elements in the range and mid gives the position of middle element. Step1: Initialize the variables low=0, high=n-1,LOC=-1 Step2: while(low<= high)do mid=(low+high)/2 Step 3: if(searchitem = = A[mid]) LOC=mid GOTO Step 6 Endif Step 4:if(searchitem<A[mid])then high=mid-1 Step 5:else low=mid+1 Endif End of while loop Step 6:if(LOC>=0)then Display ”searchitem found at position (LOC+1)” else Display “searchitem not found” Endif Step 7:Exit
  • 14. Example: Consider the elements in array A 11 22 33 44 where n=4 and search element ITEM is 11 low = 0(lower bound) high = 3(upper bound) mid = (0+3)/2 =1 ITEM<A[mid] so go to the lower half segment. Therefore reset the value of high to mid-1 low=0 high=0 mid=0 ITEM= =A[0] and search element 11 is found at position 1 (mid+1). Consider the search element 77 in the above list 11 22 33 44 low = 0(lower bound) high = 3(upper bound) mid = (0+3)/2 =1 A[mid]=22 ITEM>A[mid] so go to the upper half segment. Therefore reset the value of low to mid+1 low=2 high=3 mid=2 A[mid]=33 ITEM>A[mid] so go to the upper half segment. Therefore reset the value of low to mid+1 low=3 high=3 mid=3 a[mid]=44 ITEM>A[mid] so go to the upper half segment. Therefore reset the value of low to mid+1 low=4 Now low>high and therefore conclude that the element is not found in the list.
  • 15. /*Program to perform Binary Search using iteration*/ #include<stdio.h> int binary(int[],int,int,int); void main() { int i,key,a[20],n,loc=-1; clrscr(); printf("Enter the number of elementsn"); scanf("%d",&n); printf("enter the elementsn"); for(i=0;i<n;i++) scanf("%d",&a[i]); printf("Enter the search elementn"); scanf("%d",&key); loc=binary(a,0,n-1,key); if(loc>=0) printf("Element found at %d positionn",loc+1); else printf("Element not foundn"); getch(); }
  • 16. /*Binary search iterative function*/ int binary(int a[10],int low,int high,int item) { int mid; while(low<=high) { mid=(low+high)/2; if(item==a[mid]) return(mid); else if(item>a[mid]) low=mid+1; else if(item<a[mid]) high=mid-1; } return(-1);