当前位置:网站首页>Sort 3-select sort and merge sort (recursive implementation + non recursive implementation)
Sort 3-select sort and merge sort (recursive implementation + non recursive implementation)
2022-07-28 16:31:00 【World_ living】
Catalog
Preface

One 、 Selection sort
Selection sort : It refers to the largest... In the array to be sorted each time ( Small ) Array elements of values , Exchange the value of this array element with the value of the first array element that is not sorted .
Because it's easy to understand , Then I'll go directly to the code ( A new version of ) The maximum and minimum values are arranged together
void SelectSort(int *arr, int n)
{
for (int i = 0; i < n - 1;i++)
{
int maxi = i;
int mini = i;
for (int j = i + 1; j < n; j++)
{
// Looking for big
if (arr[j]>arr[maxi])
{
maxi = j;
}
// Looking for a small
if (arr[j] < arr[mini])
{
mini = j;
}
}
Swap(&arr[i], &arr[maxi]);
if (i==mini)// Determine whether the minimum value is on the first element of the unordered array
{
mini = maxi;
}
Swap(&arr[n - 1], &arr[mini]);
n--;
}
}
}
details : In the above code , When the minimum value is at the first element of the unsorted array , We need to judge , Otherwise, the sorting fails , So I added one in the above code if sentence .
summary :
- Time complexity :O(N2)
- Spatial complexity :O(1)
- stability : unstable
Two 、 Merge sort
Merge sort : The principle is to assume that the initial sort contains n Elements , It can be seen as n Subsequence , The length of each subsequence is 1, Then merge in pairs , obtain 【n/2】 A length of 2 or 1 An ordered subsequence of ; Merge in pairs ,…, repeat , Until you get a length of n The ordered sequence of .
Recursive implementation
- decompose : First decompose the initial sequence into n Subsequence , Just like a tree
- Merge : Then merge into ordered subsequences , repeat ( Like the post order traversal of a tree )
- We merge into the new array always , Then copy it to the original array

Code :
void _MergeSort(int* a, int left, int right, int* tmp)
{
if (left >= right)
return;
// Position of decomposition
int mid = (left + right) >> 1;
// [left, mid]
// [mid+1, right]
_MergeSort(a, left, mid, tmp);
_MergeSort(a, mid+1, right, tmp);
int begin1 = left, end1 = mid;
int begin2 = mid + 1, end2 = right;
int index = left;
// Merge
while (begin1 <= end1 && begin2 <= end2)
{
if (a[begin1] <= a[begin2])
tmp[index++] = a[begin1++];
else
tmp[index++] = a[begin2++];
}
// If a subsequence is merged , There is still a part of another subsequence that has not been merged , Then merge directly
while (begin1 <= end1)
{
tmp[index++] = a[begin1++];
}
while (begin2 <= end2)
{
tmp[index++] = a[begin2++];
}
// Copy to the original array
for(int j=left;j<=right;j++)
{
a[j]=tmp[j];
}
//memcpy(a+left, tmp+left, sizeof(int)*(right - left+1));
}
void MergeSort(int* a, int n)
{
assert(a);
int* tmp = (int*)malloc(sizeof(int)*n);// Open up space
_MergeSort(a, 0, n - 1, tmp);
free(tmp);// Finally, free up space
}
summary :
- The disadvantage of merging is that it requires O(N) Spatial complexity of , The thinking of merge sort is more about solving the problem of external sort in disk .
- Time complexity :O(N*log2N)
- Spatial complexity :O(N)
- stability : Stable
Iterative implementation ( Non recursive )
This is our big dish , In the non recursive implementation, we use some ideas of hill sorting ( grouping ), But our grouping is direct consolidation , There is no decomposition in recursion .
- hold n Subsequences are grouped in pairs , Direct sort merge into ordered (n/2) Subsequence , So back and forth .
- At this time, we define a number (gap) To divide them , And after every major merger gap Will change , So that the next segmentation .
- Each subsequence is an interval to be merged

details :
The above picture is a normal situation , Abnormal conditions are as follows

Synthesize the situation in the above figure : We need to judge and correct .
- Situation one and situation three , We can if fall , When there is no second interval to be sorted , Just jump out and merge
- For case two , We can modify the range of the interval
Code :( Pay attention to the division of intervals )
void _MergeSort(int* a,int* tmp,int begin1,int end1,int begin2,int end2)
{
int i = begin1;
int j = begin1;
while(begin1 <= end1 && begin2 <= end2)
{
// obtain a[begin1] and a[begin2] The smaller number in the , Move the smaller value
if (a[begin1] < a[begin2])
tmp[i++] = a[begin1++];
else
tmp[i++] = a[begin2++];
}
// take [begin1,end1] Put the remaining number in tmp Array
while (begin1 <= end1)
tmp[i++] = a[begin1++];
// take [begin1,end1] Put the remaining number in tmp Array
while (begin2 <= end2)
tmp[i++] = a[begin2++];
// take tmp Copy the values of the array to a Array
memcpy(a+j, tmp+j, sizeof(int) * i);
}
void MergeSortNonR(int* a,int* tmp,int n)
{
int gap = 1;
while(gap < n)
{
int i = 0;
for(i = 0;i < n;i += 2 * gap)
{
int begin1 = i,end1 = i + gap - 1,begin2 = i + gap,end2 = i + 2 * gap - 1;
// The second interval does not exist
if(begin2 >= n)
break;
// The second interval data is not enough gap individual , Correct the range
if(end2 >= n)
end2 = n - 1;
_MergeSort(a,tmp,begin1,end1,begin2,end2);
}
gap *= 2;
}
}
summary
If you have any questions, please point them out , Learning together , See you next time .
边栏推荐
- 2021-04-02
- Use py to automatically generate weekly reports based on log records
- LwIP development | realize TCP server through socket
- 2021-04-02
- Fifth uncle's thinking
- ANSYS二次开发 - MFC界面调用ADPL文件
- 一小时内学会Abaqus脚本编程秘籍
- Kubeedge releases white paper on cloud native edge computing threat model and security protection technology
- SDL2 简明教程(四):用 SDL_IMAGE 库导入图片
- 8051 series MCU firmware upgrade IAP
猜你喜欢

KubeEdge发布云原生边缘计算威胁模型及安全防护技术白皮书

flashfxp 530 User cannot log in. ftp

Image semantic segmentation practice: tensorflow deeplobv3+ train your own dataset

MySQL view event status statements and modification methods

关于web对接针式打印机问题,Lodop使用

Kubeedge releases white paper on cloud native edge computing threat model and security protection technology

ANSA二次开发 - 在PyCharm上搭建ANSA/META二次开发环境

Roson的Qt之旅#101 Qt Quick中的模型和视图

疫情红利消失,「居家健身」泡沫消散

栈的介绍与实现(详解)
随机推荐
“蔚来杯“2022牛客暑期多校训练营3 H.Hacker SAM+线段树/DP/分治(不带修查区间最大子段和)
Automatic conversion and cast
About the web docking pin printer, lodop uses
Abaqus GUI界面解决中文乱码问题(插件中文乱码也适用)
Li Hongyi, machine learning 5. Tips for neural network design
解决电脑恶意广告弹窗的思路
加速投资的小红书,“病急乱投医”?
LwIP development | realize TCP server through socket
Qt学习之Qt Designer(设计师)
I came across Digital Phoenix coordinate Xuhui Meiluo city in Shanghai
I'll show you a little chat! Summary of single merchant function modules
使用js直传oss阿里云存储文件,解决大文件上传服务器限制
500million users, four years earlier than wechat... This app, which has been in operation for 15 years, will be permanently discontinued
Roson的Qt之旅#102 ListModel
QT QString详解
The little red book of accelerating investment, "rush to medical treatment"?
R language uses file of FS package_ Delete function deletes the specified file under the specified folder, draw inferences from one instance, dir_ Delete function, link_ The delete function can be use
视频号找到金钥匙,抖音模仿后来人
Dynamic programming -- digital statistics DP
PHP image upload