[英]bubble sort in javascript - recursive version not working
我试图构建一个冒泡排序算法来对数组进行排序。 它适用于对数组进行排序,但对于它的递归实现,它永远不会停止......我知道我应该放置一些 break 子句来停止 for 循环的执行,但我不确定在哪里。
有人可以就递归函数的这些类型的问题提供一些有用的指导吗?
谢谢
input = [1, 7, 5, 6, 8, 9, 9, 100, 24, 35, 10] function bubbleSort(input) { for (let i = 0; i < input.length; i++) { if (input[i] > input[i + 1]) { let newvar = input[i]; input[i] = input[i + 1]; input[i + 1] = newvar; bubbleSort(input); } } }; console.log(bubbleSort(input));
您必须使用计数器变量来计算当前迭代并在计数器等于数组长度时返回数组
input = [1, 7, 5, 6, 8, 9, 9, 100, 24, 35, 10] function bubbleSort(input,curr){ if(curr==input.length){ return input; } for (let i = 0; i < input.length; i++) { if (input[i] > input[i + 1]) { let newvar = input[i]; input[i] = input[i + 1]; input[i + 1] = newvar; } } return bubbleSort(input,curr+1); } console.log(bubbleSort(input,0));
这是一个仅使用递归的版本 -没有for
循环 -
const bubbleSort = (a = []) => a.length < 2 ? a : cont (singlePass (a)) ( r => [ ...bubbleSort (r .slice (0, -1)) , ...r .slice (-1) ] ) const cont = x => k => k (x) const None = Symbol () const singlePass = ([ x = None, y = None, ...more ]) => y === None ? [ x ] : x === None ? [] : x > y ? [ y, ...singlePass ([ x, ...more ]) ] : [ x, ...singlePass ([ y, ...more ]) ] const input = [ 1, 7, 5, 6, 8, 9, 9, 100, 24, 35, 10 ] console .log (bubbleSort(input)) // [ 1, 5, 6, 7, 8, 9, 9, 10, 24, 35, 100 ]
如果将其打包为模块,则应仅导出bubbleSort
-
module.exports = { bubbleSort }
这是您的代码的固定版本:
input = [1,7,5,6,8,9,9,100,24,35,10] function bubbleSort(input, n) { if(n === 1) {return input;} // return when all the iterations are done for (let i = 0; i < input.length; i++) { if(input[i] > input [i+1]){ let newvar = input[i]; input[i] = input[i+1]; input[i+1] = newvar; } } return bubbleSort(input, n - 1); // Keep it outside for loop and return it to make it recursively returned }; console.log(bubbleSort(input, input.length - 1));
input = [1, 7, 5, 6, 8, 9, 9, 100, 24, 35, 10];
function bubbleSort(input) {
for (let i = 0; i < input.length; i++) {
if (input[i] > input[i + 1]) {
let newvar = input[i];
input[i] = input[i + 1];
input[i + 1] = newvar;
bubbleSort(input);
}
//return it reaches last loop of statement
***if(i == input.length -1){
return input;
}***
}
};
console.log(bubbleSort(input));
这是一种没有循环且没有变量来计算您已完成的迭代次数的解决方案:
const bubbleSort = (a, length) => {
if (length === 0) {
return a;
}
if (length === undefined) {
length = a.length;
}
return bubbleSort(a.sort((valueA, valueB) => valueA - valueB), length - 1);
};
要使用它,您只需传递需要排序的数组:
const testArr = [50, 5, 0, 10, -1];
console.log(bubbleSort(testArr)); // [ -1, 0, 5, 10, 50 ]
我不知道它是否可以比这更短并且仍然可读。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.