r/woahdude • u/rWoahDude • Nov 18 '14
gifv Sorting algorithms
http://gfycat.com/UnlawfulPaleGnat199
u/CDefense7 Nov 18 '14
As mentioned in another post where I saw this, check out this video. Needs sound.
78
u/EliteAzn Nov 18 '14
Gotta love bogosort
94
u/Remmy14 Nov 18 '14
If not Sorted
{
list.randomize();
}29
u/tagus Nov 18 '14
lmao
46
u/The_Villager Nov 18 '14
That is indeed Bogosort. Shuffle until you have it sorted. (In case you thought it was a joke... Well, Bogosort is a joke)
18
u/Tarnate Nov 18 '14
Just wait until we get quantum computers. Now THAT could get interesting.
46
u/deadstone Nov 18 '14
Quantum Bogosort
An in-joke among some computer scientists is that quantum computing could be used to effectively implement a bogosort with a time complexity of O(n).[9] First, use quantum randomness to permute the list. The quantum randomization creates n! branches of the wavefunction ("universes" in many-worlds interpretation), and one of these will be such that this single shuffle had produced the list in sorted order. The list is then inspected, and if it is not sorted, the universe is destroyed. Since destroyed universes cannot be observed, the list is always observed to have been successfully sorted after one iteration (having done O(n) work).
→ More replies (2)5
u/nxlyd Nov 18 '14
How does quantum computing differentiate between inspection and observation? How do we inspect a qubit without observing it?
→ More replies (4)1
u/Ironfruit Nov 18 '14
There is also Bogobogo sort, which nobody has mentioned yet! I believe it performs Bogo sort on the first n elements of the list starting with n=2 ( then n=3, and so on) and goes back to n=2 the first time a Bogo sort fails.
9
u/Regimardyl Nov 18 '14
It has a very good best case though. On the other hand, it might not terminate if the dataset is at least 2 elements long.
3
u/squngy Nov 18 '14
Not really, I bet the randomization is longer than most of those sorts if the list is 1 element off.
4
u/Regimardyl Nov 18 '14
The (only) best case is the list already being sorted, which causes the loop to not even start. All other starts already cause an undefined runtime.
5
u/dpekkle Nov 18 '14
Any sort can just check if the list is sorted to start if it wants to have such a "best case".
7
u/justaFluffypanda Nov 18 '14 edited Nov 18 '14
Posted this in the last thread when this was posted but I'll hijack here as well.
The more tech savy of you might like to play around with bogosort to see the amount of time it takes to sort even small arrays (i.e. 12 or 13 elements), here is a C program I wrote which will allow you to do so.
Just compile it and off you go!
edit: I'd recommend adding an optimization flag to gcc since I wrote this in class and it isn't the most elegant code I've ever put together. O3 seems to work just fine.
If it's working this is what it should look like.
2
1
21
u/Fat_Head_Carl Nov 18 '14
At first I thought you were joking about needing sound. After two in, I see it adds a ton.
2
14
11
9
u/Badoit1778 Nov 18 '14 edited Nov 18 '14
Beautiful.
Heap sort <3 (starts at 1.29)
edit - BOGO sort! - (starts at 5.18)
2
2
u/timothyj999 Nov 19 '14
That's the coolest thing I've seen in a while. If you showed this to a computer scientist in, say, the 1960's, you would be burned as a witch.
1
1
1
1
5
17
u/themitchnz Nov 18 '14
I've always liked the dancing algorithms best
Quick-sort with Hungarian (Küküllőmenti legényes)…: http://youtu.be/ywWBy6J5gz8
2
u/Mezziah187 Nov 18 '14
The song they're dancing to is so catchy it makes me want to learn how to do this dance
3
22
30
u/thesunmustdie Nov 18 '14
Example of bubble sort algorithm in Javascript. Check it out in your browsers console:
var arr = [5, 2, 3, 8, 6, 1, 4, 9, 7];
function bubbleSort(theArray) {
var i, j, temp;
for (i = theArray.length - 1; i >= 0; i--) {
for (j = 0; j <= i; j++) {
if (theArray[j] > theArray[j + 1]) {
temp = theArray[j];
theArray[j] = theArray[j + 1];
theArray[j + 1] = temp;
}
}
}
return theArray;
}
console.log('Before sort: ' + arr);
console.log('After sort: ' + bubbleSort(arr));33
u/tuna_safe_dolphin Nov 18 '14
It's a trap!
This code will steal your social security number and all of your cookies.
7
8
u/northguard Nov 18 '14
I'd add a console.log(theArray) inside the loop if people wanna follow along ea. step.
→ More replies (1)→ More replies (2)3
u/SadDragon00 Nov 18 '14
I don't know why but I always liked bubble sort in school. Just so straight forward.
1
u/ShadowSpade Nov 18 '14
I didnt even fuking think there are other sorting ways. Our sir just thought us this mehod and it was just called sorting.
7
12
u/phoenix616 Nov 18 '14
No love for Chaos Sort? :/
11
u/dustyjuicebox Nov 18 '14
Bogo sort? I don't think you could fit that in the span of a gif even with such few elements to be sorted.
42
u/gosp Nov 18 '14
Chaos sort depends on the fact that bits have a chance to spontaneously switch due to quantum mechanics.
while(true) if(List.isSorted) break;26
u/the_omega99 Nov 18 '14
I'm not familiar with the term "chaos sort" and Bogo sort is slightly different (it's akin to repetitively shuffling a deck and checking if it's sorted).
I've heard of a "quantum bogosort" joke, which worked like "check if list sorted, if not, destroy universe". To the observer in the undestroyed universe, the sorting appears to work in O(1) time.
6
1
1
u/michael1026 Nov 18 '14
I was hoping I could find information on this since I found it funny, but I couldn't unfortunately.
1
2
4
1
1
u/quchen Nov 19 '14
Even better: quantum bogosort. Input: list, many worlds interpretation.
Randomly permute the list.
If the list is not sorted, destroy the universe.
Output: the sorted list. And the universe in which it exists.
22
Nov 18 '14
I'm a computer science major who has learned a lot about this stuff. This stuff interests me like crazy. Thanks for posting.
3
u/LeSteve Nov 18 '14
I'd like to be a CS Major in college. I love this stuff. I've taken APCS and I'll be taking ATCS soon. APCS was my favourite course I've ever taken. It was one of the first things I was legitimately interested in.
I've tried coming up with my own sorting algorithms before as well. It's so crazy when one finally works, and you feel like you actually discovered something.
6
u/mikefh Nov 18 '14
...it's cool until you find that your algorithm was previously discovered and subsequently dismissed by a mathematician in the 1960's.
2
Nov 18 '14
ATCS?
2
u/LeSteve Nov 18 '14
My high school has a course for students who want to continue after APCS AB. It's a half student and half teacher led course, with the students coming up with projects to do and the teacher approving and providing the knowledge and resources necessary to achieve their goals. It's a really great course and I can't wait to take it!
1
u/ChocolateSizzle Nov 18 '14
That's so cool! I'm taking APCS right now and an really enjoying. I'm actually looking at studying History, but the logic needed for programming is still really interesting. UC app deadline is coming up, and so excited/nervous.
4
u/btchombre Nov 18 '14
No Radix sort?
3
u/dalr3th1n Nov 18 '14
Seriously. It's one of the best (by a good bit) for sets with a relatively low max value.
3
7
9
3
3
u/jacicconi Nov 18 '14
Does somebody care to explain this to me in layman's terms? Are these automated computer sorting processes?
4
Nov 18 '14
An algorithm is just a way of doing something methodically. Just like you probably can write out the steps of making a peanut butter jelly sandwich so that anybody can follow the steps and end up up with a peanut butter jelly sandwich, programmers can write out a series of steps for a computer to sort lists. Each section of the gif you see is a different algorithm (or series of steps) that a computer can take to sort a list, and how it impacts the amount of time it takes to sort the list.
1
4
u/enfrozt Nov 18 '14
Basically in programming we get lots of data.
we have 1 million out of order numbers (1, 9, -5, 2, 10...)
We can use a sorting algorithm to literally sort them from biggest to smallest or vice versa
This is just a basic ELI5, it can get a bit more complex.
3
2
2
u/Stuffyz Nov 18 '14
Can someone explain practical applications to why you would want to use a different sorting algorithms? Don't they all take place within milliseconds anyways; even on large data sets?
7
Nov 18 '14
No. Sorting is extremely slow. I generally only want to sort my data once, and never again if I can help it. This is especially the case if the comparison (A>B) is hard to compute.
As /u/LeSteve says above, the reason you might want different sorts is because they excel at different tasks. Looks like Heap sort wins at totally random, Bubble sort wins at nearly-sorted, Shell sort wins at reversed and few-unique, Quick sorts are the best overall.
Like, yes, Luigi can jump the highest in Mario 2, but Toad can carry more stuff, Mario is best overall. Which one you pick depends on what you want to optimize.
1
u/Stuffyz Nov 18 '14
Is there a cheat sheet for sorting? Something I can print/bookmark if I am ever in the situation where my current sorting methods are taking longer than an hour and therefore I can optimize it?
4
u/IDe- Nov 18 '14
If you have 100000 items and one operation takes a millisecond algorithm that takes n2 operations (e.g. insertion sort) to sort n items would take 115 days, where as one doing nlog(n) operations (e.g. quicksort) would take 8 minutes.
2
u/CellularBeing Nov 18 '14
Hi, I'm learning about this stuff now, does anyone have a good guide to understanding the big O notation for each one?
1
u/darkmighty Nov 18 '14 edited Nov 18 '14
Write the algorithm down.
For the worst case, find the worse for each step, or find a situation you know it performs poorly (and then count the steps). This will usually be at most O( n2 ).
Best case is easier -- pick a really easy case, like all sorted. If you can show it is O( n ), then you're done (usually the case).
The tricky is average case. I don't think there's an easy way out here, you just have to do the E[t]. If there are loops you can't just multiply averages (unless they're independent), you can only add averages.
Note that big-O is pretty limited in practice, unless you're dealing with massive problem sizes: the constants really matter otherwise. I think the best is testing on data you expect to sort and see how it goes, and probably securing against worst case via some analysis if it's critical.
2
2
2
2
1
1
1
1
u/Proxystarkilla Nov 18 '14
What the fuck does this even mean? To someone who doesn't know what's going on, it's just lines moving. Is this real? Is it only for coding?
2
u/KrustyBunkers Nov 19 '14
Sorting a dataset is an important programming concept. You are currently in the midst of a bunch of nerds discussing the fastest way to sort datasets based on the post.
1
Nov 18 '14
Nothing beats the king of all sorts, the Sleep Sort: http://archives.cazzaserver.com/SleepSortWiki/SleepSort.html
1
1
1
u/Ukleon Nov 18 '14
Holy crap, this is amazing. If a 36-year-old computer studies (note: not "science" - that would have been better, dammit) could have a Wonder Years-style flashback, this is it. I remember learning and writing this crap down but this animation is awesome for summarising it.
1
u/Wylkus Nov 18 '14
I'd be nice if when an algorithm finished before it's competitors it was highlighted. Then we could see easily at the end how Bubble is best at Nearly Sorted, Shell is best at Reversed, and Quick3 is best on the rest (is what it seems like anyway)
1
u/C4ples Nov 18 '14
There used to be an audio version of each of these. I'll see if I can dig it up.
EDIT: Never mind. Late to the party.
1
u/mildlyAttractiveGirl Nov 19 '14
I'm really glad I saw this post the same day that my CS355 teacher accidentally spent an entire class getting us to derive Bubble sort so we can debug some sorting algorithms the next class meeting. I showed her the AlgoRythmics YouTube channel with the sorting dances and she got really excited. I'll show her this, too.
0
1
1
1
1
1
u/Djames516 Nov 19 '14
I feel like the sample sizes need to be way larger to show the advantages of the more advanced algorithms
1
1
u/NathaNRiveraMelo Nov 19 '14
I saw this website last spring when I was talking a programming class and was enthralled by the visualization of different sorting algorithms. There's also an audiovisual representation of these algorithms and many more here:
According to my professor, computer scientists and students write many lengthy theses for their dissertations or for the sake of other computer research projects - all regarding search algorithms and their infinite nuances. Fascinating stuff.
1
1
u/Tarman183 Nov 19 '14
I used that website for a school assessment, really good..
the french version has more features but is, ya know.. in french...
1
1
1
1
1
0
0
u/random_access_cache Nov 18 '14
I remember learning this in programming class, pretty interesting subject.
0
u/somekjoo Nov 18 '14
This is only in /r/woahdude because of the animation.... half the people here probably don't even know what sorting algorithms are..
0
0
0
u/Theta_Zero Nov 18 '14
So...Always use heap, shell or insertion and ignore the others. Got it.
2
1
u/alexfrance250291 Nov 19 '14
Only if your data is random, if its nearly sorted then use Bubble! It's really not as simple as it first seems.
0
0
0
0
0
u/mick4state Nov 18 '14
I read some of Homestuck a while back, and this kind of reminds me of the sorting mechanisms the characters had for their items. Are they related or am I seeing a parallel that doesn't exist?
0
0
0
0
u/TakenChance Nov 18 '14
Man I remember being in my computer science class learning this stuff. Some are actually every simple and work very well. We also watch some video with people dancing while doing a sorting algorithm so that was a bit weird
0
0
0
0
Nov 18 '14
In many bars & clubs around the world people are figuring out line snorting algorithms 'til late in the morning...
523
u/quchen Nov 18 '14 edited Nov 18 '14
Source of the animation: http://www.sorting-algorithms.com/
Here are some very brief descriptions. Keep in mind that a list of at most one element is always sorted, which is the base case for most sorting algorithms.
Insertion sort: Pick next element, swap it through the list of already sorted elements until it's at the right place. Repeat.
Selection sort: Find the smallest element and add it to the end of the list of already sorted elements. Repeat.
Bubble: The comparison operation starts at the end of the list, comparing the last and last-but-one element, and swaps them if they are not in order. The comparison operation then "bubbles" upwards along the list in single steps, repeatedly comparing adjacent elements, and swapping them if they're not in order. At the end of such a run, the smallest element will have made its way up to the beginning of the list. Repeat this process (starting at the end again) until the list is sorted.
Shell: The idea is to produce multiple sorted sub-lists, giving you an almost ordered list, which can then be processed quicker.
Merge: Split input list in two parts, sort the parts individually. Next, merge the two sorted lists to a large sorted list. (Remember that a 1-element list is always sorted, so splitting goes on until you start merging two one-element lists.)
Heap: Build a data structure known as a heap from the elements; sort the heap, which can be done efficiently.
Quicksort: Pick an arbitrary list element, known as the pivot. Group all the other entries in groups "smaller/greater than pivot", giving you a structure smaller-pivot-larger. Recursively sort smaller/larger.
Quicksort3: Like Quicksort, but uses two pivots, resulting in smaller-p1-between-p2-larger.