Time always makes me feel a sense of frustration, and I always get used to looking around.
3.2.1 Order Lookup
The elements in the array are compared to the given lookup key until a successful match is made, or the complete number of groups is traversed, and the lookup fails. You can add a lookup key to the end of the array so that you don't have to check to see if the end of the table is reached at each iteration (and the array is inconvenient to add elements).
Code implementation:
/*** Sequential Search *@paramArray Object Arrays *@paramKey Lookup Key *@returnfind successful return element subscript, failed to return-1 **/ Public Static intSequentialsearch (int[] Array,intkey) { intI=0; while(i<array.length&&array[i]!=key) {i++; } if(i<array.length)returni; return-1; }
Algorithm Analysis:
Sequential lookups have the advantage (simplicity) and disadvantage (low efficiency) of the brute force method, which is a linear algorithm in the worst case and the average case.
3.2.2 String Matching
Problem: Given a string of n characters, called text , a string of M (m<=n) characters, becomes a pattern , finds a substring of matching patterns from the text, and finds the subscript of the leftmost element of the first matched substring in the text. Brute force method to achieve this problem, the pattern is aligned with the first m characters of the text, and then matches each pair of characters from left to right until the m matches all of the characters, or the match fails, then moves the pattern to the right one bit, continuing the attempt to match until the match succeeds or the last m character match of the text fails.
Code implementation:
/*** Brute force method string matching *@paramtext literal *@paramPattern Mode *@returnReturns the leftmost element subscript of the first matched substring in the text, matching failed failure returns-1 **/ Public Static intBruteforcestringmatch (Char[] text,Char[] pattern) { for(inti=0;i< (text.length-pattern.length+1); i++){ intJ=0; while(j<pattern.length&&text[i+j]==Pattern[j]) {J++; } if(j==pattern.length)returni; } return-1; }
Algorithm Analysis:
In the worst case, the algorithm may have to do m comparisons each time, making n-m+1 times to move, a total of M (n-m+1) comparisons. So at this point the algorithm belongs to θ (nm). For the typical problem of finding words in natural language text, we can assume that most of the moves occur after a few comparisons. So the average efficiency of the algorithm should be much better than the worst efficiency. In fact, when looking for random text, it can show linear efficiency θ (n+m), or θ (n).
Brute force Method-sequential lookup and string matching