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

Feb 24, 2025 - 10:05
 0
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

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);
}
}
}

Output:

Image description