(排序法) Merge Sort

Posted ollie-lin

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了(排序法) Merge Sort相关的知识,希望对你有一定的参考价值。

Code:

 1 #include <iostream>
 2 #include <stdio.h>
 3 #include <stdlib.h>
 4 #include <vector>
 5 
 6 using namespace std;
 7 const int Max = 1000;
 8 
 9 void merge(vector<int>& Array, int front, int mid, int end)
10 {
11     vector<int> LeftSub(Array.begin() + front, Array.begin() + mid + 1);
12     vector<int> RightSub(Array.begin() + mid + 1, Array.begin() + end + 1);
13 
14     LeftSub.insert(LeftSub.end(), Max);
15     RightSub.insert(RightSub.end(), Max);
16 
17     int idxLeft = 0, idxRight = 0;
18 
19     for (int i = front; i <= end; i++) {
20 
21         if (LeftSub[idxLeft] <= RightSub[idxRight]) {
22             Array[i] = LeftSub[idxLeft];
23             idxLeft++;
24         }
25         else{
26             Array[i] = RightSub[idxRight];
27             idxRight++;
28         }
29     }
30 }
31 
32 
33 void MergeSort(vector<int> & array, int front, int end)
34 {
35     if (front < end)
36     {
37         int mid = (front + end) / 2;
38         MergeSort(array, front, mid);
39         MergeSort(array, mid + 1, end);
40         merge(array, front, mid, end);
41     }
42 }
43 
44 void PrintArray(std::vector<int> &array){
45     for (int i = 0; i < array.size(); i++) {
46         std::cout << array[i] << " ";
47     }
48     std::cout << std::endl;
49 }
50 
51 
52 int main()
53 {
54     int arr[] = { 5, 3, 8, 6, 2, 7, 1, 4 };
55     vector<int> array(arr, arr + sizeof(arr) / sizeof(int));
56     cout << "original:" << endl;
57     PrintArray(array);
58     MergeSort(array, 0, 7);
59     std::cout << "sorted:" << endl;
60     PrintArray(array);
61     system("pause");
62     return 0;
63 }

 

以上是关于(排序法) Merge Sort的主要内容,如果未能解决你的问题,请参考以下文章

排序算法之归并排序(Merge Sort)

merge sort

合并排序(分治法)

归并排序(Merge sort)

归并排序(Merge Sort)

排序算法--Merge Sorting--归并排序--Merge sort--归并排序