我在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) );
&#13;
答案 0 :(得分:4)
if ( !arr.length ) return []
arr.splice( findSmallestIndex( arr ), 1 )
返回数组,不需要[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) );
特色链接和条款:
答案 1 :(得分:0)
这是一种更高效的方法。
function selectionSort(arr) {
var swap = function(x, y) {
var temp = arr[y];
arr[y] = arr[x];
arr[x] = temp;
}
var sort = function(start) {
if (start === arr.length) {
return arr;
}
var min = start;
for (var i = start + 1; i < arr.length; i++) {
if (arr[i] < arr[min]) {
min = i;
}
}
swap(start, min);
return sort(start + 1);
}
return sort(0);
}
selectionSort([23, 43, 23423, 66, 5, 57, 78, 0, 1]);