当前位置:网站首页>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 !
边栏推荐
- Global and Chinese market of contour projectors 2022-2028: Research Report on technology, participants, trends, market size and share
- 中電資訊-信貸業務數字化轉型如何從星空到指尖?
- Basé sur... Netcore Development blog Project Starblog - (14) Implementation of theme switching function
- Hospital network planning and design document based on GLBP protocol + application form + task statement + opening report + interim examination + literature review + PPT + weekly progress + network to
- 在尋求人類智能AI的過程中,Meta將賭注押向了自監督學習
- Add token validation in swagger
- Measurement fitting based on Halcon learning [4] measure_ arc. Hdev routine
- [UE4] parse JSON string
- The difference between MCU serial communication and parallel communication and the understanding of UART
- Sword finger offer 14- I. cut rope
猜你喜欢

Network byte order

I stepped on a foundation pit today

Crawler practice website image batch download

Pagoda SSL can't be accessed? 443 port occupied? resolvent

Have you entered the workplace since the first 00???

Database concept and installation

Johnson–Lindenstrauss Lemma
![[software implementation series] software implementation interview questions with SQL joint query diagram](/img/8b/8718fea82f83a6169ea5d8c2e5b645.jpg)
[software implementation series] software implementation interview questions with SQL joint query diagram

Add token validation in swagger

What is the difference between enterprise wechat applet and wechat applet
随机推荐
Setting methods, usage methods and common usage scenarios of environment variables in postman
How to use websocket to realize simple chat function in C #
Kiss number + close contact problem
How to use STR function of C language
1day vulnerability pushback skills practice (3)
Bugku Zhi, you have to stop him
Practical multifunctional toolbox wechat applet source code / support traffic master
Contest3145 - the 37th game of 2021 freshman individual training match_ D: Ranking
Record a problem that soft deletion fails due to warehouse level error
The difference between MCU serial communication and parallel communication and the understanding of UART
Ningde times and BYD have refuted rumors one after another. Why does someone always want to harm domestic brands?
Résumé: entropie, énergie libre, symétrie et dynamique dans le cerveau
PID of sunflower classic
Libcblas appears when installing opencv import CV2 so. 3:cannot open shared object file:NO such file or directory
Enhanced for loop
Keep an IT training diary 055- moral bitch
Www 2022 | taxoenrich: self supervised taxonomy complemented by Structural Semantics
Backpropagation formula derivation [Li Hongyi deep learning version]
2022 attached lifting scaffold worker (special type of construction work) free test questions and attached lifting scaffold worker (special type of construction work) examination papers 2022 attached
No clue about the data analysis report? After reading this introduction of smartbi, you will understand!