简体   繁体   中英

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?

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?

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. The idea is that the quicksort does not need to make as many checks and is thus faster.

Why not put in sufficient print statements to monitor what you are doing and compare that to what you arrived at on paper.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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