DEV Community

AmalaReegan
AmalaReegan

Posted on

Day26 - Searching in java: (Linear Search or (Sequential Search in Java)

searching in java:

==> In Java,searching refers to the process of finding an element in a data structure like an array,list,or map.

==> Let’s break down the main types of searching techniques:

Linear Search (Sequential Search):

Definition:

==> Linear search is a simple search algorithm where each element is checked one by one until the target is found or the end of the array is reached.

Time Complexity:

Best case:

==> O(1) — if the target is at the first index.

Worst case:

==> O(n) — if the target is at the last index or not found.

Use case:

==> Works well for small or unsorted datasets.

Example program:(While loop)

package javaprogram;

public class Linearsearch {

public static void main(String[] args) {
// TODO Auto-generated method stub

int[] arr= {10,15,8,11,55,67,7}; //0 1 2 3 4 5 6
int key=7;
int ke=8;
int i=0;

while(true)   //looping  // while(i<arr.length)  
{
if(arr[i]==key)   // if condition
{
System.out.println("key is presented:"+""+i);  //print statement
break;
}

if(arr[i]==ke)    // if condition
{
System.out.println("ke is presented:"+""+i);  //print statement
//break;
}
i++;
}
}
}
Enter fullscreen mode Exit fullscreen mode

Output:

Image description

Ex program:

package javaprogram;

public class Linearsearch1 {
public static void main(String[] args) {

// TODO Auto-generated method stub

int[] arr= {10,15,8,11,55,67,7}; //0 1 2 3 4 5 6
int key=7;
if(arr[0]==key)

{
System.out.println("key is presented"+" "+ 0);  //print statement

}
if (arr[1]==key)
{
System.out.println("key is presented"+" "+ 1);
}
if (arr[2]==key)
{
System.out.println("key is presented"+" "+ 2);
}
if (arr[3]==key)
{
System.out.println("key is presented"+" "+ 3);
}
if (arr[4]==key)
{
System.out.println("key is presented"+" "+ 4);
}
if (arr[5]==key)
{
System.out.println("key is presented"+" "+ 5);
}
if (arr[6]==key)
{
System.out.println("key is presented"+" "+ 6);
}
}
}
Enter fullscreen mode Exit fullscreen mode

Output:

Image description

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay