Linear Search
- Function for linear search.
Program
import
java.util.Scanner;
public class
LinearSearch {
private static
Scanner input;
private static int limit;
public static void
main(String[] args) {
input=new
Scanner(System.in);
System.out.println("Enter
the limit of the array:");
limit=input.nextInt();
int[]
elements=new int[limit];
System.out.println("Enter
the elements of the array:");
for(int
i=0;i<limit;i++) {
elements[i]=input.nextInt();
}
LinearSearch ob=new
LinearSearch();
ob.search(elements);
}
public void
search(int[] elements) {
int
item,flag=0;
System.out.println("Enter
the element to be searched:");
item=input.nextInt();
for(int
i=0;i<limit;i++) {
if(elements[i]==item)
{
if(flag==0)
{
System.out.println("The
element was found at position:");
}
System.out.println(i+1);
flag=1;
}
}
if(flag==0)
{
System.out.println("No
such element in the array");
}
}
}
Output
Enter
the limit of the array:
5
Enter
the elements of the array:
40
55
60
33
22
Enter
the element to be searched:
33
The
element was found at position:
4
- Function for binary search.
Program
import
java.util.Scanner;
public class
BinarySearch {
private static
Scanner input;
private static int limit;
public static void
main(String[] args) {
input=new
Scanner(System.in);
System.out.println("Enter
the limit of the array:");
limit=input.nextInt();
int[]
elements=new int[limit];
System.out.println("Enter
the elements of the array:");
for(int
i=0;i<limit;i++) {
elements[i]=input.nextInt();
}
BinarySearch ob=new
BinarySearch();
ob.search(elements);
}
public void
search(int[] elements) {
int
temp,item,mid,flag=0;
for(int
i=0;i<limit;i++) {
for(int
j=0;j<limit-1;j++) {
if(elements[j]>elements[j+1])
{
temp=elements[j];
elements[j]=elements[j+1];
elements[j+1]=temp;
}
}
}
System.out.println("The
sorted array is:");
for(int
i=0;i<limit;i++) {
System.out.println(elements[i]);
}
System.out.println("Enter
the element to be searched:");
item=input.nextInt();
mid=limit/2;
if(elements[mid]>=item)
{
for(int
i=0;i<=mid;i++) {
if(elements[i]==item)
{
if(flag==0)
{
System.out.println("Element
was found at the position:");
}
System.out.println(i+1);
flag=1;
}
}
}
else {
for(int
i=mid+1;i<limit;i++) {
if(elements[i]==item)
{
if(flag==0)
{
System.out.println("Element
was found at the position:");
}
System.out.println(i+1);
flag=1;
}
}
}
if(flag==0)
{
System.out.println("No
such element in the array!!");
}
}
}
Output
Enter
the limit of the array:
5
Enter
the elements of the array:
12
55
67
83
23
The
sorted array is:
12
23
55
67
83
Enter
the element to be searched:
23
Element
was found at the position:
2
No comments:
Post a Comment