Wrong result for Binary Search in Java -


i new programming , wrote code recursive binary search, output wrong.
tried debugging many times not know going wrong.

public class number {     public static void main (string[] args){         int []a = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19};         int key = 7;         int mid,low,high;         low=0;         high=a.length-1;         int pos=binarysearch(a,key,low,high);         system.out.println(key +" found @ "+pos+" position");     }      public static int binarysearch(int[]a,int key,int low, int high) {          int mid=(low+high)/2;          if(key<a[mid]){             high=mid-1;             binarysearch(a,key,low,high);         }         else if(key >a[mid]){             low=mid+1;             binarysearch(a,key,low,high);         }         else if(low>high){             return -1;         }         return mid;     } } 

during recursive calls execution of caller interrupted , execution frame pushed onto stack. when callee finishes execution callers frame retrieved stack , execution proceeds. assigned 9 mid , returned mid without reassigning it. if try different size arrays see initial mid returned , recursive calls made no reason. debug place 1 system.out.println("returning "+mid); in front of return statement.


Comments

Popular posts from this blog

node.js - Using Node without global install -

How to access a php class file from PHPFox framework into javascript code written in simple HTML file? -

java - Null response to php query in android, even though php works properly -