java - Is this recursive linear search code correct? -
public class recursivelinearsearch { public static void linearsearch(int[] a,int l,int x,int i) { if (l==1) { if (a[i]==x) { system.out.println("number at:"+i); return; } else return; } else { if (a[i]==x) { system.out.println("number at:"+i); return; } else { i=i+1; l=l-1; linearsearch(a,l,x,i); } } } public static void main(string[] args) { int[] a={1,2,3,4,6}; int l = 5; int x = 6; int i=0; linearsearch(a,l,x,i); } }
is recursive linear search code correct? new java wanted make sure on right track.how can code improved?
what advantage of recursive linear search non recursive case?
regarding algorithm:
recursive algorithms consist of 1 or more base cases , recursive call(s):
in case have 2 base cases, length zero , number @ first position:
if (length == 0) { return; } else if (a[i]==x) { system.out.println("number at:"+i); return; } ...
(the first base case length == 1 because, last element not element searching for)
after base case(s) add recursive call(s) if no base case applies:
... else { i++; length--; linearsearch(a,length,x,i); }
the resulting code this:
public static void linearsearch(int[] a, int length, int x, int i) { if (length == 0) { return; } else if (a[i]==x) { system.out.println("number at:"+i); return; } else { i++; length--; linearsearch(a,length,x,i); } }
while did not try run code sample, should equivalent code, cleaner.
if want learn more recursive algorithms, suggest modify (or :)) code use divide-and-conquer approach. (less recursive calls, avoids stackoverflow on large arrays)
the wikipedia article on recursion place start if haven't had @ it.
variable naming:
avoid using 1 lettered variables. while might make sense while programming, other people read code (or later) not know variable contains until have @ variable used , why. great example parameter l of linearsearch method.
linearsearch(int[] a, int length, int x, int i)
code style:
while partially caused pasting here, seem use multiple code styles programs. not big problem improve readability of code (and therefore maintainability).
personally prefer keeping curly brackets on same line method or if statement have done main method.
Comments
Post a Comment