简体   繁体   English

如何告诉快速排序算法它应该终止?

[英]How can I tell a quicksort algorithm that it should terminate?

Ok, so I've just started to learn about sorting algorithms in school.好的,所以我刚刚开始在学校学习排序算法。 I think I know the concept of quicksort pretty well as I can perform on it a piece of paper.我想我非常了解快速排序的概念,因为我可以在一张纸上执行它。 However, with a piece of paper, I know when to stop and that's when the array is sorted.但是,有了一张纸,我就知道什么时候该停下来,也就是对数组进行排序的时候。 But if I check the array all the time to see if it is sorted, that defies the purpose of quicksort which (I think) is not to check if it's sorted many many times with it's recursion.但是,如果我一直检查数组以查看它是否已排序,那就违背了快速排序的目的,(我认为)不是检查它是否通过递归多次排序。 Do I have to just keep recursing it down to when there is only 1 element left in the array when it is by definition sorted or is there some other way to terminate it?当数组按定义排序时,我是否必须继续递归到数组中只剩下 1 个元素时,还是有其他方法可以终止它?

Do I have to just keep recursing it down to when there is only 1 element left in the array when it is by definition sorted or is there some other way to terminate it?当数组按定义排序时,我是否必须继续递归到数组中只剩下 1 个元素时,还是有其他方法可以终止它?

Yes, that is exactly how quicksort should terminate.是的,这正是快速排序应该终止的方式。

The fact that you need to make the checks you mention does not mean it is inefficient.您需要进行您提到的检查这一事实并不意味着它效率低下。 This is no different than selection sorts or bubble sorts which also have to check various conditions and swap elements.这与selection sortsbubble sorts没有什么不同,它们也必须检查各种条件和交换元素。 The idea is that the quicksort does not need to make as many checks and is thus faster.这个想法是quicksort不需要进行尽可能多的检查,因此速度更快。

Why not put in sufficient print statements to monitor what you are doing and compare that to what you arrived at on paper.为什么不放入足够的打印报表来监控您正在做的事情并将其与您在纸上得出的结果进行比较。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM