当前位置:网站首页>Easy to win insert sort
Easy to win insert sort
2022-07-04 03:09:00 【Little orange learns programming】
Easily take down the insert sort !!!
1、 Insertion sort
What is insert sort ?
A focus on Insert , Extract one element at a time as a temporary element , After comparing and moving in turn
Core rules :
- In the first round , Pull away The penultimate element at the end of the array , As Temporary elements
- Compare the temporary element with the element after the array : If The value of the following element is smaller than that of the temporary element , be The following element moves left
- If the following element is larger than the temporary element , Or it has moved to the end of the array , Then insert the temporary element into the current air attack
- Repeat the above steps , To complete the order
The core logic here is through each iteration , take Some elements are arranged in order , After a certain number of iterations , Achieve the effect of final sorting
give an example :
The first iteration :
- First select the penultimate element 5 As a temporary element
- Compare the temporary elements with the following elements in turn ,5 Than 3 Big , So it will 3 One left
- At this point, we have reached the end of the array , Direct will 5 Insert
Second iteration :
- First select the penultimate element 7 As a temporary element
- Compare with the following elements in turn ,7 Than 3 Big , take 3 One left
- Next 7 And 5 Compare ,7 Than 5 Big , So it will 5 One left
- The end of the array has been reached , Direct will 7 Insert
The third iteration :
- First select the penultimate element 4 As a temporary element
- Compare with the following elements in turn ,4 Than 3 Big , take 3 One left
- 4 Than 5 Small , Direct will 4 Insert the current gap position
We can find out : Each iteration can add The elements at the end are in order
Time complexity :
The best situation
If all the elements are arranged in ascending order , We Each iteration does not require moving elements , So time complexity is O(N)
The worst case scenario
If all the elements are in descending order , We Each iteration and the comparison in the iteration need to move , under these circumstances , The number of steps to compare is :
O((N^2 + N) / 2)
, The number of steps to move is :O((N^2 + N) / 2)
. So the worst case is :O(N^2 + N)
, Ignore that the constant is :O(N^2)
The code is as follows :
public static void insertSort(int[] array) {
// Start from the penultimate place , Traverse to the end 0 position , Traverse N-1 Time
for (int i = array.length - 2; i >= 0; i--) {
// Store the currently extracted elements
int temp = array[i];
// Start traversing from the right side of the extracted element
int j = i + 1;
while (j <= array.length - 1) {
// If an element , Less than temporary elements , Then this element moves left one
if (array[j] < temp) {
array[j - 1] = array[j];
} else {
// If it is greater than , Then insert the temporary element directly , And then exit the loop
array[j - 1] = temp;
break;
}
j++;
}
// Deal with reaching the tail
if (j == array.length) {
array[j - 1] = temp;
}
}
}
Bubble sort vs Selection sort vs Insertion sort
Bubble sort and insert sort can refer to orange Easily get bubble sort and select sort This article ~
First , Bubble sort is definitely poor . Selection sorting and insertion sorting depend on the situation
If The original array itself has many elements that have reached the desired sorting state and are in good order , So choose Insertion sort ( For example, the best case cited above , near O(N) ). Otherwise select Selection sort
therefore , In practice , Or we should choose the corresponding algorithm according to the characteristics of real data
2、 Optimize insert sort - Bisection insertion sort
The core logic of the insertion algorithm is to find the location of the temporary element that should be inserted , It is similar to querying in an ordered array , Find where the element should be inserted
As shown in the figure :
The pictures are selected from the official website of youkeda learning
The second iteration is equivalent to the result of the first iteration [3,5]
Search for 7 Where it should be inserted . The third iteration is equivalent to the result of the second iteration [3,5,7]
Search for 4 Where it should be inserted
In fact, for this kind of ordered list , Loop traversal is not the optimal solution , There's a better way : Dichotomy search
therefore , The efficiency of sorting can be further improved by combining insertion sorting and binary search
Bisection method
// Find the location of the index that should be inserted
public static int searchIndex(int[] array, int left, int right, int aim) {
while (left < right) {
int middle = (right + left) / 2;
int value = array[middle];
if (value < aim) {
left = middle + 1;
} else {
right = middle - 1;
}
}
// If the final element is still larger than the target element , Move the index position to the left ( Judge the current element and the target element , See if you need to insert before the current element )
if (array[left] > aim) {
return left - 1;
}
// Otherwise, it is to return to the current position
return left;
}
array: Original array
left and right: The interval to be inserted
aim: Target element to be inserted
Insert sort code optimization
Modify the insertion sort code again , Direct use of searchIndex
The insertion position queried :
public static void insertSort(int[] array) {
// Start from the penultimate place , Traverse to the end 0 position , Traverse N-1 Time
for (int i = array.length - 2; i >= 0; i--) {
// Store the currently extracted elements
int temp = array[i];
int index = searchIndex(array, i+1, array.length-1, temp);
// According to the inserted index position , Move and insert the array . After obtaining the position to be inserted , Move the following elements in turn , Then insert
int j = i + 1;
while (j <= index) {
array[j - 1] = array[j];
j++;
}
array[j - 1] = temp;
}
}
I hope this article can get your approval ~~~ If you think this article is useful, remember to give the thumbs-up + Focus on , Or share it with your friends , I also hope you can give little orange some suggestions , Let's cheer together !
边栏推荐
- Setting methods, usage methods and common usage scenarios of environment variables in postman
- [untitled] the relationship between the metauniverse and digital collections
- Practical multifunctional toolbox wechat applet source code / support traffic master
- The first spring of the new year | a full set of property management application templates are presented, and Bi construction is "out of the box"
- [database I] database overview, common commands, view the table structure of 'demo data', simple query, condition query, sorting data, data processing function (single row processing function), groupi
- Sword finger offer 20 String representing numeric value
- In my spare time, I like to write some technical blogs and read some useless books. If you want to read more of my original articles, you can follow my personal wechat official account up technology c
- 96% of the collected traffic is prevented by bubble mart of cloud hosting
- Jenkins continuous integration environment construction V (Jenkins common construction triggers)
- (practice C language every day) pointer sorting problem
猜你喜欢
96% of the collected traffic is prevented by bubble mart of cloud hosting
Comment la transformation numérique du crédit d'information de la Chine passe - t - elle du ciel au bout des doigts?
Stm32bug [the project references devices, files or libraries that are not installed appear in keilmdk]
What are the conditions for the opening of Tiktok live broadcast preview?
Rhcsa day 3
C learning notes: C foundation - Language & characteristics interpretation
Backpropagation formula derivation [Li Hongyi deep learning version]
在尋求人類智能AI的過程中,Meta將賭注押向了自監督學習
Teach you how to optimize SQL
Redis notes (I) Linux installation process of redis
随机推荐
VRRP+BFD
Lichuang EDA learning notes 14: PCB board canvas settings
How to use websocket to realize simple chat function in C #
Add token validation in swagger
Experience summary of the 12th Blue Bridge Cup (written for the first time)
Résumé des outils communs et des points techniques de l'examen PMP
Osnabrueck University | overview of specific architectures in the field of reinforcement learning
Tsinghua University product: penalty gradient norm improves generalization of deep learning model
Stm32bug [the project references devices, files or libraries that are not installed appear in keilmdk]
POSTECH | option compatible reward reverse reinforcement learning
Safety tips - seat belt suddenly fails to pull? High speed police remind you how to use safety belts in a standardized way
Imperial cms7.5 imitation "D9 download station" software application download website source code
Global and Chinese markets for electroencephalogram (EEG) devices 2022-2028: Research Report on technology, participants, trends, market size and share
WP collection plug-in free WordPress collection hang up plug-in
中電資訊-信貸業務數字化轉型如何從星空到指尖?
Advanced learning of MySQL -- Application -- index
Short math guide for latex by Michael downs
7 * 24-hour business without interruption! Practice of applying multiple live landing in rookie villages
C language black Technology: Archimedes spiral! Novel, interesting, advanced~
60 year old people buy medical insurance and recommend a better product