By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
 454,128 Members | 1,059 Online
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,128 IT Pros & Developers. It's quick & easy.

# recurrsive function goes into infinte loop

 P: 62 hi, i have a functionn sort_and_count where i will sort a vector and count the number of inversions. i will first divide the list into two n call the function recurrsively. problem is its going on,doesnt stop. please can you tell me why is this problem here? this implements merge sort also. here's the sample code: Expand|Select|Wrap|Line Numbers int sort_and_count(int Left,int Right) {      int Mid;      int count=0,countL=0,countR=0;      if(Left==Right)      {           return count=0;      }      else      {           Mid=(Left+Right+1)/2;           countL = sort_and_count(Left,Mid);           countR = sort_and_count(Mid+1,Right);           count = merge_count(Left,Mid,Right);           return count=count+countL+countR;      }     } thank you in advance.. Mar 11 '07 #1
Share this Question
3 Replies

 P: 63 hi, i have a functionn sort_and_count where i will sort a vector and count the number of inversions. i will first divide the list into two n call the function recurrsively. problem is its going on,doesnt stop. please can you tell me why is this problem here? this implements merge sort also. here's the sample code: Expand|Select|Wrap|Line Numbers int sort_and_count(int Left,int Right) {      int Mid;      int count=0,countL=0,countR=0;      if(Left==Right)      {           return count=0;      }      else      {           Mid=(Left+Right+1)/2;           countL = sort_and_count(Left,Mid);           countR = sort_and_count(Mid+1,Right);           count = merge_count(Left,Mid,Right);           return count=count+countL+countR;      }     } thank you in advance.. There is something wrong with your equation 1 = (0 + 1 + 1)/2 // Integral math In the next line you state sort_and_count(Left,Mid); since Mid == Right, you’ll get into an infinite loop here. Any time the difference between left and right is 1, then Mid == Right therefore you’ll never get to the base case of left == right Mar 11 '07 #2

 P: 63 Maybe (note that I haven’t try it) if your base case is: if((Right == Left) || (Right – Left = 1)) Mar 11 '07 #3

 P: 62 There is something wrong with your equation 1 = (0 + 1 + 1)/2 // Integral math In the next line you state sort_and_count(Left,Mid); since Mid == Right, you’ll get into an infinite loop here. Any time the difference between left and right is 1, then Mid == Right therefore you’ll never get to the base case of left == right thanks for the insight...i have resolved the error... the equations should be : mid = (left+right)/2 Mar 13 '07 #4

### Post your reply

Sign in to post your reply or Sign up for a free account.