Help with printing iterations
Ok not sure how to print the iterations for this program. Below is my code and what I have tried so far but im not sure im doing it right. Im supposed to be testing binary vs linear and printing the iterations.
Code:
import java.io.*;
import java.text.DecimalFormat;
import java.util.*;
class Search
{
public static int iterations;
// seek target in the array of strings.
// return the index where found, or -1 if not found.
public static int seqSearch( int[] array, int searchItem )
{
iterations = 0;
for ( int j=0; j < array.length; j++ ){
iterations++;
if ( array[j] == searchItem)
return j ; // Target found.
}
return -1 ; // Target not found
}
public static int binSearch(int [] array, int searchItem)
{
iterations = 0;
int start = 0;
int end = array.length-1;
int mid;
while (start <= end)
{
iterations++;
mid = (start+end)/2;
if (searchItem == array[mid])
{
return mid;
}
else if (searchItem < array[mid])
{
end = mid-1;
}
else
{
start = mid+1;
}
}
return -1;
}
static Scanner kb = new Scanner(System.in);
public static void main(String []args)
{
int[] numList= new int[20];
numList[0]=5;
numList[1]=10;
numList[2]=15;
numList[3]=20;
numList[4]=25;
numList[5]=30;
numList[6]=35;
numList[7]=40;
numList[8]=45;
numList[9]=50;
numList[10]=55;
numList[11]=60;
numList[12]=65;
numList[13]=70;
numList[14]=75;
numList[15]=80;
numList[16]=85;
numList[17]=90;
numList[18]=95;
numList[19]=100;
int j= seqSearch(numList, 75);
if(j != -1){
System.out.println("found at position" + j);
} else {
System.out.println("not found");
int j= binSearch(numList,75);
if(j != -1){
System.out.println("found at position" + j);
} else {
System.out.println("not found");
}
}
}
}