归并排序:归并排序采用分治的思想,先将已经有序的子序列合并,得到有序的序列,即使每个子序列有序,再是子序列段间有序。
归并排序的基本思想:将待排序的序列看成n个长度为1的序列,将相邻的有序表成对归并,得到n/2个长度为2的有序表;按照前面的方法依次进行
知道合并成长度为n的有序序列。
归并排序要做两件事:1、分解 2、合并
const int MaxSize = 100;
void Merge(int *arr, int low, int mid, int high){//合并
if(low < high){
int arrC[MaxSize];//静态分配内存
for(int k = low;k <= high;k++) arrC[k] = arr[k];
int i = low;
int j = mid + 1;
while(i <= mid && j <= high){
if(arrC[i] < arrC[j])
arr[low++] = arrC[i++];
else
arr[low++] = arrC[j++];
}
while(i <= mid) arr[low++] = arrC[i++];
while(j <= high) arr[low++] = arrC[j++];
}
}
void MergeSort(int *arr, int low,int high){//归并函数
int mid;
if(low < high){
mid = (low + high) / 2;
MergeSort(arr, low, mid);
MergeSort(arr, mid+1, high);
Merge(arr, low, mid, high);
}
}
void Merge(int *arr, int low, int mid, int high){//合并
if(low < high){
int *arrC = (int*)malloc((high-low+1)*sizeof(int));//动态分配内存
int k = 0;
int i = low;
int j = mid + 1;
while(i <= mid && j <= high){
if(arr[i] < arr[j])
arrC[k++] = arr[i++];
else
arrC[k++] = arr[j++];
}
while(i <= mid) arrC[k++] = arr[i++];
while(j <= high) arrC[k++] = arr[j++];
for(int i = 0;i < k;i ++)
arr[low++] = arrC[i];
}
}
void MergeSort(int *arr, int low,int high){//归并函数
int mid;
if(low < high){
mid = (low + high) / 2;
MergeSort(arr, low, mid);
MergeSort(arr, mid+1, high);
Merge(arr, low, mid, high);
}
}