﻿ Java exercises and solutions: search element of array

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

}

} thambiduraiJava program to subtract the following array inputs, a = { 0 , 4 , 6 , 8 , 10} b = {3 , 2 , 11 , 8 , 4} 2017-06-12