This content originally appeared on DEV Community and was authored by Saravanan
Linear Search:
int[] ar = {10,45,67,100}
int key = 67;
for(int i=0;i<ar.length;i++)
{
if(ar[i]==key)
System.out.println("key is presented :"+i);
}
output:
key is presented :2
Binary Search:
int[] ar = {10,16,18,21,27,37, 45, 98,100};
int key = 18;
int max_idx = ar.length-1;
int min_idx=0;
while(min_idx<=max_idx)
{
int mid_idx=(min_idx+max_idx)/2;
if(ar[mid_idx]==key)
{
System.out.println("key is present :" + mid_idx);
break;
}
else if(key>ar[mid_idx])
{
min_idx= mid_idx+1;
}
else if(key<ar[mid_idx])
{
max_idx= mid_idx-1;
}
}
output:
key is present :2
This content originally appeared on DEV Community and was authored by Saravanan
Print
Share
Comment
Cite
Upload
Translate
Updates
There are no updates yet.
Click the Upload button above to add an update.

APA
MLA
Saravanan | Sciencx (2025-02-24T17:42:49+00:00) Linear search and Binary search programs. Retrieved from https://www.scien.cx/2025/02/24/linear-search-and-binary-search-programs/
" » Linear search and Binary search programs." Saravanan | Sciencx - Monday February 24, 2025, https://www.scien.cx/2025/02/24/linear-search-and-binary-search-programs/
HARVARDSaravanan | Sciencx Monday February 24, 2025 » Linear search and Binary search programs., viewed ,<https://www.scien.cx/2025/02/24/linear-search-and-binary-search-programs/>
VANCOUVERSaravanan | Sciencx - » Linear search and Binary search programs. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2025/02/24/linear-search-and-binary-search-programs/
CHICAGO" » Linear search and Binary search programs." Saravanan | Sciencx - Accessed . https://www.scien.cx/2025/02/24/linear-search-and-binary-search-programs/
IEEE" » Linear search and Binary search programs." Saravanan | Sciencx [Online]. Available: https://www.scien.cx/2025/02/24/linear-search-and-binary-search-programs/. [Accessed: ]
rf:citation » Linear search and Binary search programs | Saravanan | Sciencx | https://www.scien.cx/2025/02/24/linear-search-and-binary-search-programs/ |
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.