当前位置:网站首页>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 .
边栏推荐
- PHP image synthesis technology
- 加速投资的小红书,“病急乱投医”?
- PHP mb_ Substr Chinese garbled code
- I came across Digital Phoenix coordinate Xuhui Meiluo city in Shanghai
- php关于数据量大导出数据或者遍历数据导致内存溢出超时等问题
- ANSA二次开发 - 在PyCharm上搭建ANSA/META二次开发环境
- 李宏毅《机器学习》丨4. Deep Learning(深度学习)
- 一大早支付宝来短信说你中“奖”了?处理服务器挖矿病毒 - kthreaddi
- ANSYS二次开发 - MFC界面调用ADPL文件
- 优化Hypermesh脚本性能的几点建议
猜你喜欢

Food safety | these two kinds of melons and fruits should be improved, especially for pregnant women with constipation

头条文章_signature

资本「断供」两年,我只能把公司卖了

Deeply understand the fusing configuration of istio traffic management

学会使用MySQL的Explain执行计划,SQL性能调优从此不再困难

Stm32cube infrared remote control: input capture

Paging query in applet

Is MySQL query limit 1000,10 as fast as limit 10? If I want to page, what should I do?

SCI scientific paper writing Growth Camp (full version)

QT packaging
随机推荐
正大杯黑客马拉松数据解析竞赛
大地坐标系转换火星坐标系
LwIP development | realize TCP server through socket
Detailed explanation of QT qstring
A program for judging the result of cyclic input
flashfxp 530 User cannot log in. ftp
“蔚来杯“2022牛客暑期多校训练营3 A.Ancestor LCA+暴力计数
信号屏蔽与处理
The epidemic dividend disappeared, and the "home fitness" foam dissipated
关于web对接针式打印机问题,Lodop使用
Leetcode topic
Zhaoqi science and technology innovation and entrepreneurship competition talent introduction platform, mass entrepreneurship and entrepreneurship competition high-level talent introduction
R language uses ggpairs function of ggally package to visualize pairwise relationship graph of grouping multivariable, set alpha parameter to change image transparency, diagonal continuous variable de
关于标准IO缓冲区的问题
ANSA二次开发 - 抽中面的两种方法
flashfxp 530 User cannot log in. ftp
PHP 图片上传
深入理解Istio流量管理的熔断配置
Brief tutorial for soft exam system architecture designer | software debugging
Numpy ndarray learning < II > miscellaneous records