Insertion Sorting
Explanation of inserting Sorting
Consider that when we have a set of pocker cards in our hands, how will we sort them? Normally, we will start with the third card, and find a right place to insert it in. This is how insertion sort works.
To start with, assuming we have this set of numbers and we want to sort it in inscending order:
1 |
|
1 |
|
Firstly, we can consider that the first number is sorted, so we take the second number. To find the right position of 6, we need to compare it from the last number in the sorted list (which is the first number), if the number is larger than it, then we swap them. Otherwise, we move foward in the sorted list and compare it with that number. Because there is no next number in the sorted list in this condition, we will finish swap and 6 has find its position.
Repeat to do the process n(the length of array) times, the whole array is sorted because all elements are inserted into correct position.
Pros and Cons of inserting Sorting
Pros
- Negligible storage space is used. (Only a temp variable)
- It is stable.
Cons
- The time complexity is O(n2), which is bad.
Implementation
Java
1 |
|
Python
1 |
|
本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!