If on the other hand nums isn't the smallest, then its value plays no role whatsoever in determining idx_min. If nums is the smallest in nums, then we don't really swap and nums remains as it is, i.e., remains completely random. And it is: It is at the very beginning, and what's done inside the outer loop keeps this property. said: The still-to-be-sorted part nums looks completely random. Try it yourself, select the sorting algorithms on the right, then click "Start".įor selection sort, we see what John L. It visualizes sorting many arrays in parallel, each array is a column, index 0 is on top, and dark colors are "smaller" than bright colors. Using a fabulous sort visualizer (taken from this), here's random data and how the data looks midway through sorting with the two algorithms. Less mathematical, but I think also insightful. Also see asker's wonderful and enlightening explanation. The reason is embodied in the proof of two claims above. Where the second equality and the fourth equality use the growth rate of partial sums of harmonic series and the second equality from the last uses Stirling's approximation. Print(' n exchangeSort selectionSort ratio') For exchange sort it looks quadratic, for selection sort maybe linearithmic?Ĭode ( Try it online!): def exchangeSort(nums): What's the expected number of trues for each?. Why is it so much more often? Does someone have a good explanation? I did expect some noticeable difference, but not this much. For example for 8000 random numbers, in exchange sort it's true ~270 times more often: trues in trues in Exchange sort is similar to selection sort, just swaps "overly eagerly" instead of finding the minimum and doing only one swap.
0 Comments
Leave a Reply. |