Ana*_*eva 0 javascript sorting algorithm recursion
我正在用 JavaScript 编写递归选择排序。
预期行为:我希望函数selectionSort()按升序对数组中的值进行排序。
问题:我无法摆脱递归,我不知道如何。
错误:
Uncaught RangeError: Maximum call stack size exceeded
const findSmallestIndex = ( arr ) => {
let smallest = arr[0];
let smallestIndex = 0;
let arrLen = arr.length;
for ( let i = 0; i < arrLen; i++ ) {
if ( arr[i] < smallest ) {
smallest = arr[i];
smallestIndex = i;
}
}
return smallestIndex;
};
const selectionSort = ( arr ) => {
let smallest = arr.splice( findSmallestIndex( arr ), 1 );
return [smallest].concat( selectionSort( arr ) );
};
let arr = [23, 43, 23423, 66, 5, 57, 78, 0, 1];
console.log( selectionSort(arr) );Run Code Online (Sandbox Code Playgroud)
if ( !arr.length ) return []arr.splice( findSmallestIndex( arr ), 1 )返回 Array 并且不需要 in [smallest]...- 只是smallest.concat( selectionSort( arr ) )arr(由ftor指出),因此我们可以通过添加来修复它let newArray = Array.prototype.slice.call( arr );/**
* Finds smallest element of an aray
* @param {Array} arr array for searching
* @return {number} index of the smallest element in array
*/
const findSmallestIndex = ( arr ) => {
let smallest = arr[0];
let smallestIndex = 0;
let arrLen = arr.length;
for ( let i = 0; i < arrLen; i++ ) {
if ( arr[i] < smallest ) {
smallest = arr[i];
smallestIndex = i;
}
}
return smallestIndex;
};
/**
* Sorts recursively an array of numbers
* @param {Array} arr An array of numbers
* @return {Array} New sorted array
*/
const selectionSort = ( arr ) => {
if ( !arr.length ) return [];
let newArray = Array.prototype.slice.call( arr );
let smallest = arr.splice( findSmallestIndex( arr ), 1 );
return smallest.concat( selectionSort( arr ) );
};
let arr = [23, 43, 23423, 66, 5, 57, 78, 0, 1];
console.log( selectionSort(arr) );Run Code Online (Sandbox Code Playgroud)
精选链接和条款: