算法系列—自顶向下归并排序(递归)
2016-10-22 16:48
246 查看
#include <iostream>
//函数声明
void sort(int A[], int tempArry[], int lo, int hi);
void merge(int A[], int tempArry[], int lo, int mid, int hi);
void MERGESORT(int A[], int size);
void MERGESORT(int A[],int size)
{
int *aux = new int[size]; //临时存放合并的序列
sort(A, aux, 0, size - 1);
}
void sort(int A[],int tempArry[],int lo,int hi)
{
if (hi <= lo)
return;
int mid = lo + (hi - lo)/2;
sort(A, tempArry, lo, mid);
sort(A, tempArry, mid + 1, hi);
merge(A, tempArry, lo, mid, hi);
}
void merge(int A[],int tempArry[],int lo,int mid,int hi)
{
int i = lo, j = mid + 1;
for(int k=lo;k<=hi;k++)
{
tempArry[k] = A[k];
}
for(int k=lo;k<=hi;k++)
{
if (i > mid)
A[k] = tempArry[j++];
else if (j > hi)
A[k] = tempArry[i++];
else if (tempArry[j] > tempArry[i])
A[k] = tempArry[i++];
else
A[k] = tempArry[j++];
}
}
int main() //test
{
int A[] = { 1,4,6,4,7,4,10,50,88,2,33,56,3,345,66,67,4 };
MERGESORT(A, sizeof(A) / 4);
for(auto a:A)
{
std::cout << a<<" ";
}
}
//函数声明
void sort(int A[], int tempArry[], int lo, int hi);
void merge(int A[], int tempArry[], int lo, int mid, int hi);
void MERGESORT(int A[], int size);
void MERGESORT(int A[],int size)
{
int *aux = new int[size]; //临时存放合并的序列
sort(A, aux, 0, size - 1);
}
void sort(int A[],int tempArry[],int lo,int hi)
{
if (hi <= lo)
return;
int mid = lo + (hi - lo)/2;
sort(A, tempArry, lo, mid);
sort(A, tempArry, mid + 1, hi);
merge(A, tempArry, lo, mid, hi);
}
void merge(int A[],int tempArry[],int lo,int mid,int hi)
{
int i = lo, j = mid + 1;
for(int k=lo;k<=hi;k++)
{
tempArry[k] = A[k];
}
for(int k=lo;k<=hi;k++)
{
if (i > mid)
A[k] = tempArry[j++];
else if (j > hi)
A[k] = tempArry[i++];
else if (tempArry[j] > tempArry[i])
A[k] = tempArry[i++];
else
A[k] = tempArry[j++];
}
}
int main() //test
{
int A[] = { 1,4,6,4,7,4,10,50,88,2,33,56,3,345,66,67,4 };
MERGESORT(A, sizeof(A) / 4);
for(auto a:A)
{
std::cout << a<<" ";
}
}
相关文章推荐
- 算法学习(10)-递归 之归并排序
- 算法学习(10)-递归 之归并排序
- 小游戏系列算法之四扫雷游戏核心算法,非递归无雷区自动翻开
- 算法入门之归并排序(自顶向下方法)
- 【数据结构&&算法系列】归并排序简单介绍及python代码
- C/C++面试之算法系列--菲波拉契数列的递归与非递归算法
- 【从零学习经典算法系列】分治策略实例——归并排序(Mergesort)
- 算法系列之十二:多边形区域填充算法--递归种子填充算法 .
- 白话经典算法系列之九 从归并排序到数列的逆序数对(微软笔试题)
- 【从零学习经典算法系列】分治与递归1——递归表达式与解法初步
- 算法熟记-排序系列-归并排序
- 算法系列之十五:循环和递归在算法中的应用
- 算法系列之十二:多边形区域填充算法--递归种子填充算法
- 算法系列之十二:多边形区域填充算法--递归种子填充算法
- C语言实现快排、归并排序、快排改进算法的递归和非递归算法
- 算法学习(10)-递归 之归并排序
- 算法系列之十二:多边形区域填充算法--递归种子填充算法
- 零基础算法系列代码_用递归实现进制转换
- 每天学习算法系列—内部排序之归并排序和快速排序
- 【从零学习经典算法系列】分治与递归2——主方法