合并排序的c++实现

来源:互联网 发布:数据报网络 编辑:程序博客网 时间:2024/06/07 07:31

用递归实现合并排序

基本思路:定义Merge函数:输入三个数组,把前两个有序数组按照大小顺序输入到第三个数组中去。

                   定义Mergesort函数:输入一个无序数组,把它分成两半,递归的对每一半做Mergsort处理,这样这两半数组已经有序,再用Merge函数合并这两个数组到原无序数 组中去。

伪代码:

Merge(B[0..p − 1], C[0..q − 1], A[0..p + q − 1])
//Merges two sorted arrays into one sorted array
//Input: Arrays B[0..p − 1]and C[0..q − 1]both sorted
//Output: Sorted array A[0..p + q − 1]of the elements of B and C
 i ← 0; j ← 0; k ← 0
while i < p and j < q do
   if B[i]≤ C[j]
       A[k]← B[i]; i ← i + 1
   else A[k]← C[j]; j ← j + 1
       k ← k + 1
if i = p
   copy C[j..q − 1]to A[k..p + q − 1]
   else copy B[i..p − 1]to A[k..p + q − 1]



 
Mergesort(A[0..n − 1])
//Sorts array A[0..n − 1]by recursive mergesort
//Input: An array A[0..n − 1]of orderable elements
//Output: Array A[0..n − 1]sorted in nondecreasing order
if n > 1
    copy A[0..?n/2? − 1]to B[0..?n/2? − 1]
    copy A[?n/2?..n − 1]to C[0..?n/2? − 1]
    Mergesort(B[0..?n/2? − 1])
    Mergesort(C[0..?n/2? − 1])
    Merge(B, C, A) 

#include#includeusing std::ceil;#define VALUETYPE doublevoid Merge(VALUETYPE *a, VALUETYPE *b, VALUETYPE *c,int n);void Mergesort(VALUETYPE *a, int n);int main(){int alen;std::cout << "please enter the length of the array you want to slove: ";std::cin >> alen;VALUETYPE *a = new VALUETYPE[alen];for (int i = 0; i < alen; i++){std::cout << "a[" << i + 1 << "]: ";std::cin >> a[i];}Mergesort(a, alen);std::cout << "The array after sorting is as follows: \n";for (int i = 0; i < alen; i++){std::cout << "a[" << i + 1 << "]: " << a[i] << std::endl;}system("pause");return 0;}void Merge(VALUETYPE *a, VALUETYPE *b, VALUETYPE *c,int n){int Aend = n / 2;int Bend = ceil(n / 2.0);int aindex = 0;int bindex = 0;int cindex = 0;while ((aindex < Aend) && (bindex < Bend)){if (a[aindex] < b[bindex]){c[cindex++] = a[aindex++];}else{c[cindex++] = b[bindex++];}}if (aindex == Aend){for (int i = cindex ; i < n; ++i){c[i] = b[bindex++];}}else{for (int i = cindex; i < n; ++i){c[i] = a[aindex++];}}}void Mergesort(VALUETYPE *a, int n){if (n > 1){VALUETYPE *a1 = new VALUETYPE[n / 2];VALUETYPE *a2 = new VALUETYPE[ceil(n / 2.0)];int i = 0;for (;i < (n / 2); i++){a1[i] = a[i];}for (int j = 0; j < ceil(n/2.0); j++){a2[j] = a[i++];}Mergesort(a1, n / 2);Mergesort(a2, ceil(n / 2.0));Merge(a1, a2, a, n);delete[]a1;delete[]a2;}return;}

原创粉丝点击