Search code examples
arraysalgorithmrecursionpseudocode

Find Min and Max values with single recursive structure Pseudocode


I'm looking for a single recursive structure algorithm to find both maximum and minimum values of an array. I've found the following pseudocode on here:

FindMaxAndMin(A, max, min)
    if (|A| == 1)
        if (max < A[1])
            max = A[1]
        if (min > A[1])
            min = A[1]
        return (min, max)
    cen = |A| /2
    l = A[:cen-1]
    h = A[cen:]
    (min, max) = FindMaxAndMin(l, min, max)
    (min, max) = FindMaxAndMin(h, min, max)
    return (min, max)

So I was wondering firstly if this counts as a single recursive structure as it all takes place under the first if. If this is a single recursive structure, I was firstly wondering what |A| represents, can't find it anywhere online, and how would it work call by call when A = (3,2,4,1) for example?


Solution

  • |A| is just the length of the array

    you can debug and follow the steps here

    (becuse i use js i couldnt return 2 values thats way i changes it to an array

    keep in mind that minMax[0] = min

    and minMax[1] = max

    i initilized minMax[0] (min) with MAX_SAFE_INTEGER

    and minMax[0] (max) with MIN_SAFE_INTEGER)

    const FindMaxAndMin = (A, minMax)=>{
        if (A.length === 1){
            if (minMax[1] < A[0])
                minMax[1] = A[0]
            if (minMax[0] > A[0])
                minMax[0] = A[0]
            return minMax
        }
        let cen = A.length /2
        let l = A.slice(0,cen)
        let h = A.slice(cen,A.length)
        minMax = FindMaxAndMin(l, minMax)
        minMax = FindMaxAndMin(h, minMax)
        return minMax
      }
      
      console.log(FindMaxAndMin([3,4,1,2],[Number.MAX_SAFE_INTEGER , Number.MIN_SAFE_INTEGER]))