0

Sorting algorithms 📚

 1 year ago
source link: https://bernhardfritz.github.io/p8g/blog/2023/04/06/sorting-algorithms/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Sorting algorithms 📚

April 6, 2023 · 3 min read

Nearly every standard library offers data structures that can be sorted without really thinking about it. Still, it might come in handy to know about commonly used sorting algorithms or even implement some of them yourself as an exercise. After all, most sorting algorithms make heavy use of array indexing and recursion, and for this reason alone, they are often used as a medium to learn about and apply these concepts.

Even though sorting algorithms can be categorized by just a handful of different methods, there are hundreds of variations out there. Some algorithms are more efficient than others. You can compare their efficiency by both time complexity and memory consumption. It is worth noting that some sorting algorithms may perform worse in certain situations while, on average, they perform better than others. Finally, a stable sorting algorithm is expected to preserve the order of elements considered to be equal.

As you can tell, choosing the right sorting algorithm may not always be so easy. For this reason, I have compiled the following list, including implementation details for future reference:

NameBest
Average
Worst
MemoryStableMethodVisualization
Quicksortnlog⁡nn \log nnlogn
nlog⁡nn \log nnlogn
n2n^2n2
log⁡n\log nlognNoPartitioningquicksort.gif
Merge sortnlog⁡nn \log nnlogn
nlog⁡nn \log nnlogn
nlog⁡nn \log nnlogn
nnnYesMergingmerge-sort.gif
Heapsortnlog⁡nn \log nnlogn
nlog⁡nn \log nnlogn
nlog⁡nn \log nnlogn
1NoSelectionheapsort.gif
Insertion sortnnn
n2n^2n2
n2n^2n2
1YesInsertioninsertion-sort.gif
Selection sortn2n^2n2
n2n^2n2
n2n^2n2
1NoSelectionselection-sort.gif
Shellsortnlog⁡nn \log nnlogn
n43n^{4 \over 3}n34​
n32n^{3 \over 2}n23​
1NoInsertionshellsort.gif
Bubble sortnnn
n2n^2n2
n2n^2n2
1YesExchangingbubble-sort.gif

Further reading


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK