原理
https://www.cnblogs.com/chengxiao/p/6194356.html
算法步骤
利用分治策略
特点
C++实现
void Solution::merge_sort(vector<int>& array)
{
int len = array.size();
if (len > 1) {
_merge_sort_pro(array, 0, len - 1);
}
}
void Solution::_merge_sort_pro(vector<int>& array, int leftIdx, int rightIdx)
{
if (leftIdx < rightIdx) {
//int midIdx = leftIdx + ((rightIdx - leftIdx) >> 1)
int midIdx = leftIdx + (rightIdx - leftIdx) / 2;
_merge_sort_pro(array, leftIdx, midIdx);
_merge_sort_pro(array, midIdx + 1, rightIdx);
_merge(array, leftIdx, midIdx, rightIdx);
}
}
void Solution::_merge(vector<int>& array, int leftIdx,int midIdx, int rightIdx)
{
int size = rightIdx - leftIdx + 1;
vector<int> help(size, 0);
int p1 = leftIdx, p2 = midIdx + 1;
int i = 0;
while (p1 <= midIdx && p2 <= rightIdx) {
help[i++] = array[p1] < array[p2] ? array[p1++] : array[p2++];
}
while (p1 <= midIdx) {
help[i++] = array[p1++];
}
while (p2 <= rightIdx) {
help[i++] = array[p2++];
}
for (int i = 0; i < help.size(); i++) {
array[leftIdx + i] = help[i];
}
}
C实现
//合并相邻有序数组时,要新建一个额外的数组
void merge_array(int array[], int left_index, int center_index, int right_index, int n)
{
int* pTmp = new int[n];
int i = left_index;//左序列指针
int j = center_index + 1;//右序列指针
int t = 0;//临时数组索引
//合并数组
while (i <= center_index && j <= right_index)
{
if (array[i] < array[j])
{
pTmp[t++] = array[i++];
}
else
{
pTmp[t++] = array[j++];
}
}
//上面的步骤在执行完后,左或右边都有可能剩余若干个元素,
//而另一边的元素肯定已全部复制到新数组,这时需要特殊对待剩下的元素
while (j <= right_index)
pTmp[t++] = array[j++];
while (i <= center_index)
pTmp[t++] = array[i++];
t = 0;//此处注意置为0
while (left_index <= right_index)
{
array[left_index++] = pTmp[t++];
}
delete[] pTmp;
}
//分两段后,再分别递归分隔数组直至为单个元素(看作有序数组),再调用merge_array进行有序数组合并
void sub_merge_sort(int array[], int left_index, int right_index)
{
if (left_index < right_index)
{
int center_index = (left_index + right_index) / 2;//取得中点
//将原来的数组分成两段
sub_merge_sort(array, left_index, center_index);
sub_merge_sort(array, center_index + 1, right_index);
//合并刚才分开的两段,得到原来序列的有序序列
merge_array(array, left_index, center_index, right_index, right_index - left_index + 1);
}
}
void merge_sort(int array[], int array_len)
{
sub_merge_sort(array, 0, array_len - 1);
}
int main()
{
int array[10] = {21,32,34,4, 4,3,5,1,2,3 };
int array_len = sizeof(array) / sizeof(array[0]);
merge_sort(array, array_len);
for (int i = 0; i < array_len; i++)
{
cout << array[i] << " ";
}
cout << endl;
return 0;
}