Javascript:如何通过递归函数对数组进行排序 [英] Javascript: how to sort an array by recursive function

查看:68
本文介绍了Javascript:如何通过递归函数对数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用递归函数对数组进行排序。如果它已经排序,它必须返回true,否则必须返回false。



我尝试过:



我试过这样的事情`



I need to sort an array using recursive function.If it sortedthen it must return true, otherwise must return false.

What I have tried:

I have tried like this`

function sort(x, i=0){
	if(i == x.length){
		return x;
	}
		if(x[i-1] > x[i]){
        var tmp = x[i - 1];
        x[i - 1] = x[i];
        x[i] = tmp;
	}
	return sort(x, i+1);
}
console.log(sort([2,5,100,6,85,12,45]));

推荐答案

如果这是一个真正的问题,请使用数组。 prototype.sort() - JavaScript | MDN [ ^ ]



如果这是家庭作业或面试问题,那么你需要做自己的研究。 (您还需要从更随机的数字数组开始,以查看您提出的算法落在何处。) Wikipedia已最受欢迎的排序算法列表 [ ^ ]让你入门。
If this is a genuine question, then use Array.prototype.sort() - JavaScript | MDN[^]

If this is a homework or interview question, then you'll need to do your own research. (You'll also want to start with a more random array of numbers, to see where your proposed algorithm falls over.) Wikipedia has a good list of the most popular sorting algorithms[^] to get you started.


Quote:

我需要对数组进行排序使用递归函数。如果它排序则必须返回true,否则必须返回false。

I need to sort an array using recursive function.If it sorted then it must return true, otherwise must return false.



只是声明没有意义!

排序函数将返回排序的数组,没有别的。

无论你选择哪种解决方案,都需要选择算法然后转换为代码。递归不是强制性的,它是你的选择。



我们不做你的HomeWork。

HomeWork问题是那种简化版本你必须在现实生活中解决的问题,目的是学习和练习。你想要的那种帮助就像试图通过让别人为你训练来打破奥运纪录,因为你是初学者。



HomeWork不会测试你的乞求其他人做你的工作的技巧,它会让你思考并帮助你的老师检查你对所学课程的理解,以及你应用它们时遇到的问题。

你的任何失败都会帮助你的老师发现你的弱点并设定补救措施。

你的任何失败都会帮助你了解什么有效,什么无效,被称为'试错'学习。

所以,试一试,重读课程并开始工作。如果您遇到特定问题,请展示您的代码并解释这个问题,我们可能会提供帮助。


Just the statement makes no sense !
A sort function will return the sorted array, nothing else.
What ever the solution you choose, you need to select an algorithm and then translate to code. Recursive is not mandatory, it is your choice.

We do not do your HomeWork.
HomeWork problems are simplified versions of the kind of problems you will have to solve in real life, their purpose is learning and practicing. The kind of help you want is like trying to break an olympic record by having someone else trainning for you because you are a beginner.

HomeWork is not set to test your skills at begging other people to do your work, it is set to make you think and to help your teacher to check your understanding of the courses you have taken and also the problems you have at applying them.
Any failure of you will help your teacher spot your weaknesses and set remedial actions.
Any failure of you will help you to learn what works and what don't, it is called 'trial and error' learning.
So, give it a try, reread your lessons and start working. If you are stuck on a specific problem, show your code and explain this exact problem, we might help.


这篇关于Javascript:如何通过递归函数对数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆