Breaking out of a recursion in java

后端 未结 11 1464
故里飘歌
故里飘歌 2020-12-01 04:23

The recursion is sort of a \'divide and conquer\' style, it splits up while getting smaller (Tree data structure), and I want it to break completely if a violation is found,

11条回答
  •  心在旅途
    2020-12-01 05:14

    What you are asking is the definition of recursion.

    At some point all recursive paths should break. Otherwise it will be an infinite recursion and stack overflow exception occurs.

    So you should design the recursion function like that. An example binary search in a sorted array:

    BinarySearch(A[0..N-1], value, low, high) {
           if (high < low)
               return -1 // not found
           mid = low + ((high - low) / 2)  // Note: not (low + high) / 2 !!
           if (A[mid] > value)
               return BinarySearch(A, value, low, mid-1)
           else if (A[mid] < value)
               return BinarySearch(A, value, mid+1, high)
           else
               return mid // found
    }
    

提交回复
热议问题