当前位置:网站首页>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 .
边栏推荐
- 软考 系统架构设计师 简明教程 | 软件调试
- 使用js直传oss阿里云存储文件,解决大文件上传服务器限制
- 1. Simple command line connection to database
- LabVIEW LINX Toolkit控制Arduino设备(拓展篇—1)
- “蔚来杯“2022牛客暑期多校训练营3 A.Ancestor LCA+暴力计数
- PHP image upload
- Geodetic coordinate system to Martian coordinate system
- Use js direct OSS to store files in Alibaba cloud and solve the limitation of large file upload server
- 排序2-冒泡排序与快速排序(递归加非递归讲解)
- 500million users, four years earlier than wechat... This app, which has been in operation for 15 years, will be permanently discontinued
猜你喜欢

为什么学编程的人大多数都去了深圳和北京?

排序1-插入排序与希尔排序

laravel

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

使用js直传oss阿里云存储文件,解决大文件上传服务器限制

HyperMesh自动保存(增强版)插件使用说明

头条文章_signature

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

Paging query in applet

Kubeedge releases white paper on cloud native edge computing threat model and security protection technology
随机推荐
About standard IO buffers
Detailed explanation of QT qstring
动态规划 --- 数位统计DP
A program for judging the result of cyclic input
LwIP development | socket | DNS domain name resolution
大地坐标系转换火星坐标系
ffmpeg获取首帧
Huada chip hc32f4a0 realizes RS485 communication DMA transceiver
PHP image synthesis technology
PHP mb_ Substr Chinese garbled code
What does it remote operation and maintenance mean? Which is the best remote operation and maintenance software?
Writing of factorial
CoDeSys realizes bubble sorting
redis源码优化--绑核
curl无输出返回空白或者null问题解决
Sdl2 concise tutorial (4): using SDL_ Image library importing pictures
魏建军骑宝马也追不上李书福
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
Practical development tutorial of software problem repair tracking system (Part 1)
Automatic conversion and cast