if (intArray[k] == sn) found = true; return found; } } Figure 13.13, Output #1 Figure 13.13, Output #2 Did you understand why this algorithm is called inefficient? What Linear Search happens when the search number is the very first number in the list? The loop still continues and compares every element in the array until the end. This is flat silly. Imagine that you are at a car repair shop and after your file is found, the clerk continues to check every file. The next search algorithm is a more civilized and uses a Boolean variable both to signal that the requested Linear Search element is found as well as a loop condition to terminate the search. Figure 13.9 compares the previous with the improved algorithm and program. Linear Search Figure 13.14 Inefficient Linear Search Efficient Linear Search public boolean linearSearch(int SN) public boolean linearSearch(int sn) { { boolean found = false; boolean found = false; for (int k = 0; k < Size; k++) int k = 0; if (intArray[k] == sn) (k < size && !found) found = true; { return found; if (intArray[k] == sn) } = true; else k++; } return found; } Java1312.java, in figure 13.15, demonstrates the altered algorithm. Do not expect to see any difference in execution With today's computers, you will need to search a rather substantial list size to make any measurable comparisons.
if (intArray[k] == sn) found = true; return found; } } Figure 13.13, Output #1 Figure 13.13, Output #2 Did you understand why this Linear Search algorithm is called inefficient? What happens when the search number is the very first number in the list? The loop still continues and compares every element in the array until the end. This is flat silly. Imagine that you are at a car repair shop and after your file is found, the clerk continues to check every file. The next search algorithm is a more civilized Linear Search and uses a Boolean variable both to signal that the requested element is found as well as a loop condition to terminate the search. Figure 13.9 compares the previous Linear Search with the improved algorithm and program. Figure 13.14 Inefficient Linear Search Efficient Linear Search public boolean linearSearch(int SN) { boolean found = false; for (int k = 0; k < Size; k++) if (intArray[k] == sn) found = true; return found; } public boolean linearSearch(int sn) { boolean found = false; int k = 0; (k < size && !found) { if (intArray[k] == sn) = true; else k++; } return found; } Java1312.java, in figure 13.15, demonstrates the altered algorithm. Do not expect to see any difference in execution With today's computers, you will need to search a rather substantial list size to make any measurable comparisons.
Text13-Algorithms.docx