[英]Implementation of Bottom Up Merge Sort
我了解到合并排序是一种遵循分而治之原则的排序算法,它的平均时间复杂度为 n(log n)。
在这里,我将大小为 n 的数组划分为子数组(以长度 2 初始化),并通过对子数组进行排序来克服它。 然后我们以 2 的倍数继续范围,直到它小于数组的长度(即 2,4,8,....i 其中 i< 数组的长度)。
当它超过数组长度时,函数返回排序后的数组。
我使用了两个函数来实现合并排序:
该程序运行良好,我想知道我是否理解合并排序的概念并正确实现它?
//C++ Code
#include<iostream>
// Print
void print(int *arr, int length);
// To Sort the sub array
void insertion_sort(int *arr, int low, int high)
{
for(int i = high; (i-1)>=low; i--)
{
if (arr[i] < arr [i-1])
{
int temp = arr[i];
arr[i] = arr[i-1];
arr[i-1] = temp;
}
}
}
int *merge_sort(int* arr, int length, int index = 2)
{
if (length <= index) // Terminating Condition
{
return arr;
}
// The range is defined by index.
/*
If array has 8 elements: ********
It will sort array until it's range within the length of array.
1st call 2*1 elements max: ** ** ** ** // 2 set as default argument
2nd call 2*2 elements max: **** ****
3rd call 2*3 elements max: ********
Returns Array
*/
// The range is defined by index.
for(int i=0; (i+index)<length; i+=index)
{
// Divide and Sort
insertion_sort(arr, i, i+index);
}
// The range will increase in multiple of 2 (i.e. 2,4,8,....i where i<length of array)
return merge_sort(arr, length, index*2);
}
int main()
{
int length;
std::cout<<"Length of Array: ";
std::cin>>length;
int arr[length];
for(int i=0; i<length; i++)
{
std::cout<<"Enter element "<<i+1<<" : ";
std::cin>>arr[i];
}
int *result = merge_sort(arr, length);
print(result, length);
return 0;
}
void print(int *arr, int length)
{
std::cout<<"Sorted Array: ";
for(int i=0; i<length; i++)
{
std::cout<<arr[i]<<" ";
}
std::cout<<"\n";
}
纯自底向上合并排序将 n 个元素的数组划分为 n 个大小为 1 的游程,然后每次通过合并偶数和奇数游程。 链接到维基示例:
https://en.wikipedia.org/wiki/Merge_sort#Bottom-up_implementation
正如 Wiki 示例评论中所建议的,每次通过都可以更改合并方向。 为了在原始数组中得到排序的数据,计算所需的传递次数,如果传递次数是奇数,比较和交换(如果需要)元素对以创建大小为 2 的运行,然后进行合并排序通过。
对于混合插入+归并排序,对pass数做同样的计算,如果pass数为奇数,则设置initial run size为32个元素,否则设置initial run size为64个元素。 使用插入排序对初始运行进行单遍排序,然后切换到合并排序。
获取通过计数的简单示例代码(对于 32 位构建,假设 n <= 2^31):
size_t GetPassCount(size_t n) // return # passes
{
size_t i = 0;
for(size_t s = 1; s < n; s <<= 1)
i += 1;
return(i);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.