All recursions can be rewritten as loops

Recursion requires a return

function fn(n){
    console.log(n)
    if(n===0) {// debugger;
        return 0
    }
    else{
    	// debugger;
        fn(n-1) +1 
    }
}
fn(3)
Copy the code

  • Without a return, a function stuck on the call stack cannot be assigned a value level by level

Minimizing an indeterminate array recursively

  • Recursion is progression and then regression
  • Recursion is only when you keep calling your own function
  • To be executed before proceeding to an end point
/ / write 1
function min(. arr){// The number... Converted to an array
	console.log(arr.length);
    if(arr.length===2) {let minNumber=Math.min.apply(null,arr);
    	return minNumber
    }else{
    	return min(arr[0],min(... arr.slice(1)));
        // Note that you must return
        // If you want to return the function to the end of the progression, all the functions in the progression process will be executed successfully
	}
}
min(1.2.3.4.5.6.7)
Copy the code
/ / write 2
function min(arr){// Pass the array directly
    if(arr.length===2) {let minNumber=Math.min.apply(null,arr);
    	return minNumber
    }else{
    	return min([arr[0],min(arr.slice(1))); } } min([1.2.3.4.5.6.7])
Copy the code

Write sort recursively from small to large (select sort)

function sort2([a,b]){ // This notation specifies that you need to pass an array of 2 elements
   returna>b? [b,a]:[a,b]; }function minIndex(arr){
	return arr.indexOf(Math.min.apply(null,arr))
}
function sort3([a,b,c]){
	let arr=[a,b,c];
    let i = minIndex([a,b,c])
    let minResult=arr.splice(i,1)
    let result=minResult.concat(sort2(arr))
    return result
}
sort3([3.2.1])
function sort4([a,b,c,d]){
	let arr=[a,b,c,d];
    let i = minIndex([a,b,c,d])
    let minResult=arr.splice(i,1)
    let result=minResult.concat(sort3(arr))
    return result
}
// The pattern is captured by the above process
function minIndex(arr){
	return arr.indexOf(Math.min.apply(null,arr))
}
function sort2([a,b]){ // This notation specifies that you need to pass an array of 2 elements
   returna>b? [b,a]:[a,b]; }function sort(arr){
	if(arr.length===2) {return  sort2(arr)
	}else{
      let i = minIndex(arr)
      let minResult=arr.splice(i,1)
      let result=minResult.concat(sort(arr))
      return result
	}    
}
sort([5.2.1.3])
Copy the code

Queue FIFO

The restaurant is called demo and the first to get the number is the first to eat

Stack LIFO

  • Take the direct elevator
  • Call stack

List linked list

  • Every object in JS has a prototype chain which is essentially a linked list
  • The simplest linked list is a single necklace list, just go down
  • It could be a bidirectional list
  • It can also be a circular linked list with the last node pointing to the head

This is a loose and buggy linked list operation

Hash table

The tree