简体   繁体   中英

how to check array is sorted or not using recursion in javascript?

I am trying to write one function which give me array is sorted or not .if it sorted then return true else false .I want to do this using recursion

n = [1, 2, 3]
function isSorted(arr, n) {
    if (n > arr.length || n ==0) {
        return false
    }

    if (arr[n] < arr[n-1]) {
        return false
    } else {
        return true
    }
    return isSorted(arr,n-1)
}

console.log(isSorted(n,n.length-1))

currently it is giving me false but expected true

update

function isSorted(arr, n) {
    if (n ==0 || n ==1) {
        return false
    }

    if (arr[n] < arr[n-1]) {
        return false
    } else {
        return true
    }
    return isSorted(arr,n-1)
}

console.log(isSorted(n,n.length-1))

Start with the base case: if an array is length 1 or 0, then it's sorted.

Otherwise, it's only sorted if the first element is less than or equal to the second and the rest of the array is also sorted. In code, that might look like:

 function isSorted(arr) { return arr.length <= 1 ? true : arr[0] <= arr[1] && isSorted(arr.slice(1)) } console.log(isSorted([1, 2, 3 ])) console.log(isSorted([1, 1, 1 ])) console.log(isSorted([0])) console.log(isSorted([1, 4, 3 ]))

There is no need to create new array objects (as would occur when using slice ). You can just recursively iterate through the original array, as shown by the check function:

 function isSorted(arr) { var i = 0; var last = arr.length - 1; return (function check() { return (i >= last) || (arr[i] <= arr[++i] && check()); })(); } console.log(isSorted([1, 2, 3 ])) console.log(isSorted([1, 1, 1 ])) console.log(isSorted([0])) console.log(isSorted([])) console.log(isSorted([1, 4, 3 ])) console.log(isSorted([10, 5])) console.log(isSorted([3, 5, 0]))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM