Java exercises and solutions: search element of array


Java arrays

Exercise 1: By using the sequential search algorithm, write a Java program to search for an element of an integer array of 10 elements.

Solution:

public class SquentialSearch{

public static void main(String[] args){
int[] arr={23,2,4,56,80,23,4,5,6,10};
//searching by using the sequential search technique
int pos=seqsearch(arr,56, arr.length);
if(pos!=-1) System.out.println(" The values is found at the position of "+ pos);

}

public static int seqsearch(int[] dataset,int target,int n){
int found=0;
int i;
int pos=-1;
for(i=0;i<n && found!=1;i++)
  if(target==dataset[i]){pos=i;found=1;}

return pos;
  }

}

Exercise 2: Modify the Java code in exercise 1 to search for an element of the array by using binary search algorithm.

Solution:

public class BinarySearch{


public static void main(String[] args){
int[] arr={23,2,4,56,80,23,12,34,5,23};
//searching by using the binary search technique
int pos=binsearch(arr,56, arr.length);
if(pos!=-1) System.out.println(" The values is found at the position of "+ pos);

}

public static int binsearch(int[] dataset,int target, int n){
insertsort(dataset,n);//make sure the list sorted
int i;
int pos=-1;
int found=0;

if(target<dataset[n/2]){//look in the first half
for(i=0;i<n/2 && found!=1;i++)
if(target==dataset[i]){ found=1;pos=i;}
}
else{ //look in the second haft
for(i=n/2;i<n && found!=1;i++)
if(target==dataset[i]){ found=1;pos=i;}
}


return pos;
}

public static void insertsort(int[] dataset, int n)
{

int i, j;
for (i = 1; i < n; i++)
{
int pick_item = dataset[i];
int inserted = 0;
for (j = i - 1; j >= 0 && inserted != 1; )
{
if (pick_item < dataset[j])
{
dataset[j + 1] = dataset[j];
j--;
dataset[j + 1] = pick_item;
}
else inserted = 1;
      }
    }

  }

}




Comments

thambidurai comment

 thambidurai

Java program to subtract the following array inputs, a[5] = { 0 , 4 , 6 , 8 , 10} b[6] = {3 , 2 , 11 , 8 , 4}


2017-06-12



This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.