preface
Since many algorithm problems in LeetCode involve some basic data structures, in order to better understand the animation of some complex problems updated later, a new series —– “Illustrated Data Structures” is launched, mainly using animation to describe common data structures and algorithms. This series includes ten kinds, heap, queue, tree, and search set, graph and so on about dozens of articles.
Selection sort
Selection sort is a simple and intuitive sorting algorithm, whatever data goes in is O(n²) time complexity. So when you use it, the smaller the data, the better. The only benefit might be that it doesn’t take up any extra memory.
Algorithm steps
-
First find the smallest (large) element in the unsorted sequence and store it at the beginning of the sorted sequence
-
Find the smallest (largest) element from the remaining unsorted elements and place it at the end of the sorted sequence.
-
Repeat the second step until all elements are sorted.
Source: github.com/hustcc/JS-S…
Algorithm demo
Sort animation process explanation
-
Linearly search the sequence and find the minimum, which is 2
-
Replace the minimum with the number at the left end of the sequence, swapping 2 with 4
-
Now the 2 is sorted
-
We continue linear search through the rest of the sequence to find the minimum, and we find 3
-
Replace the minimum with the number at the left end of the sequence, swapping 3 and 4
-
So we’ve sorted 2 and 3
-
We continue to linearly search the rest of the sequence to find the minimum, and we find 4
-
If the minimum value is already on the left, nothing is done, so nothing is done at this point
-
At this point, 2, 3, and 4 are sorted
-
Repeat until all numbers are sorted
Code implementation
In order to better let readers use their familiar programming language to understand animation, the author will post a variety of programming language reference code, code all from the Internet.
C++ code implementation
Java code implementation
JavaScript code implementation
Python code implementation
If you’re an iOS developer, you can go to GitHub at github.com/MisterBooo/… Get more intuitive debug run source code.
If you want to get high definition animation demonstration, in the five minutes to learn the algorithm public account to reply to select sort.