Write a Java class to perform the following: 1. Write a method to search the fol
ID: 3772442 • Letter: W
Question
Write a Java class to perform the following:
1. Write a method to search the following array using a linear search, ( target elements: 11, 55, 17.). (count the number of comparisons needed).
{06, 02, 04, 07, 11, 09, 50, 62, 43, 32, 13, 75, 01, 46, 88, 17}
2. Write a method to sort the array using Selection Sort. (count the number of comparisons needed)
3, Write a method to sort the array using Bubble Sort. (count the number of comparisons needed)
4, Search he sorted array using a binary search (recursive) for the same set of target elemens. (count the number of comparisons needed)
Explanation / Answer
1
linear search
public class linearsearch
{
public static void main(String[] args)
{
int[] arr={11,15,17}
System.out.println(linearsearch(arr,06));
}
public static int linearsearch(int[] a,int element)
{
for (int i=0;i<a.length;i++)
{
if(a[i]==element) return i;
}
return -1;
}
}
2
selection sort
public static selectionsort
{
index=i,j;
for(int i=0;i<arr.length-1;i++)
{
for (int j=i+1;j<arr.length;j++)
if (arr[j]<arr[index])
int sn= arr[index];
arr[index]=arr[i];
arr[i]=sn;
}
public static void main(String[] args)
{
int[] a1={4,1,7,10};
int[] a2={12,35,2,3};
for(int i:a2)
{
System.out.println(i);
}
3
bubble sort
public class bubble sort
public static void main(String[] args)
{
int[] arr={4,1,7,9,10};
sort(arr);
for(int i:arr)
system.out.println(i);
}
{
public static void sort(int[] a)
int temp;
for(int i=0;i<a.length-1;i++)
{
for(int j=0;j<a.length-1-i;j++)
{
if(a[i]>a[j+1]
{
temp=a[0];
a[0]=a[1];
a[1]=temp;
4
binary search
public static int binarysearch(int[] a,int element)
int f=0;
int l=a.length-1;
int m=(f+l)/2;
while(f<=l)
{
if(a[m]==element)
{
return m;
}
else if(element>a[m])
{
f=m+1;
}
else
{
l=m-1;
}
m=(f+l)/2;
}
return-1;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.