I am trying to output results of a linear search with the following pieces of code:
My Print Method:
System.out.print("\nEnter a value for linear search ---> ");
int key =input.nextInt();
if (linear_search(array,key) == -1)
System.out.println("Value not found");
else System.out.println("The value is indexed at [" + linear_search(array,key) + "]");
My Search Method:
public static int linear_search(int[] list, int key){
int comparisonCount = 0;
for (int i = 0; i<list.length; i++){
comparisonCount++;
if (key == list[i]){
System.out.print(comparisonCount + " comparisons were made. ");
return i;
}
}
return -1;
}
My issue is that the bolded area is printing twice. This is what my output is looking like:
9936 9895 9637 9293 7951 7696 7667 6073 3019 2565
1178 806 183
Enter a value for linear search ---> 183
13 comparisons were made. 13 comparisons were made. The value is indexed at [12]
How can I get rid of the duplicated line?
Thanks for any advice!

New Topic/Question
Reply



MultiQuote




|