I'm using the following method to perform a Linear Search on an Array:
private int[] theArray = new int[50];
private int arraySize = 10;
public String linearSearchForValue(int value){
boolean valueInArray = false;
String indexsWithValue = "";
for(int i = 0; i < arraySize; i++) {
if(theArray[i] == value) {
valueInArray = true;
indexsWithValue+= i + " ";
}
printHorzArray(i, -1);
}
if(!valueInArray){
indexsWithValue = "None";
}
System.out.print("The Value was Found in the Following: " + indexsWithValue);
System.out.println();
return indexsWithValue;
}
// Print Array
public void printHorzArray(int i, int j) {
for(int n = 0; n < 51; n++) {
System.out.print("-");
}
System.out.println();
for(int n = 0; n < arraySize; n++) {
System.out.print("| " + n + " ");
}
System.out.println("|");
for(int n = 0; n < 51; n++) {
System.out.print("-");
}
System.out.println();
for(int n = 0; n < arraySize; n++) {
System.out.print("| " + theArray[n] + " ");
}
In the linearSearchForValue method, what is the purpose of setting indexsWithValue
to an empty string. In the if statement indexsWithValue+= i + " ";
the empty string is then added to i + " "
. I do not understand the purpose of doing these two things.
Note: The array elements are randomly generated.
You do not need it. It is just for outputting.
indexsWithValue+= i + " ";
make sure you concatenate all the indices which matches.
Your Output will be like.
i1 i2 i3 ....
where i1,i2,... are the matches found.