Algorithmic Implementation series(3) Implementation of Merge_Sort
来源:互联网 发布:linux scp传文件夹 编辑:程序博客网 时间:2024/06/06 03:59
Compiler: gcc 4.7.3
C++11
1 #include <iostream>
2
3 using namespace std;
4
5 void MERGE(int ia[], const size_t p, const size_t q, const size_t r) {
6 const size_t n1 = q - p + 1, n2 = r - q;
7 int L[n1 + 1], R[n2 + 1];
8 for(size_t i = 0; i != n1; ++i) {
9 L[i] = ia[p + i - 1];
10 }
11
12 for(size_t j = 0; j != n2; ++j) {
13 R[j] = ia[q + j];
14 }
15
16 L[n1] = -1;
17 R[n2] = -1;
18
19 size_t i = 0, j = 0;
20
21 for(size_t k = p - 1; k != r - 1; ++k) {
22 if(L[i] <= R[j]) {
23 ia[k] = L[i];
24 ++i;
25 if(L[i] == -1) {
26 ++k;
27 while(k != r) {
28 ia[k] = R[j];
29 ++k;
30 ++j;
31 }
32 break;
33 }
34 }
35 else {
36 ia[k] = R[j];
37 ++j;
38 if(R[j] == -1) {
39 ++k;
40 while(k != r) {
41 ia[k] = L[i];
42 ++k;
43 ++i;
44 }
45 break;
46 }
47 }
48 }
49 }
50
51 void MERGE_SORT(int ia[], const size_t p, const size_t r) {
52 if(p < r) {
53 size_t q = (p + r) / 2;
54 MERGE_SORT(ia, p, q);
55 MERGE_SORT(ia, q + 1, r);
56 MERGE(ia, p, q, r);
57 }
58 }
59
60 int main() {
61 int ia[] = {6, 1, 8, 3, 9, 5, 56, 43, 43, 234, 87, 56, 5, 234, 11};
62
63 const size_t size = sizeof(ia)/sizeof(int);
64
65 cout << "The original array is: " << endl;
66 for(size_t i = 0; i != size; ++i) {
67 cout << *(ia + i) << " ";
68 }
69 cout << endl;
70 MERGE_SORT(ia, 1, size);
71
72 cout << "=============================" << endl;
73
74 cout << "The sorted array is: " << endl;
75 for(size_t i = 0; i != size; ++i) {
76 cout << *(ia + i) << " ";
77 }
78 cout << endl;
79
80 return EXIT_SUCCESS;
81 }
82
- Algorithmic Implementation series(3) Implementation of Merge_Sort
- Algorithmic Implementation series(5) Implementation of Heap_Sort
- Algorithmic Implementation series(6) Implementation of Quick_Sort
- Algorithmic Implementation series(7) Implementation of Randomized_Quick_Sort
- Algorithmic Implementation series(8) Implementation of Counting_Sort
- Algorithmic Implementation series(1)——Implementation of Insertion_sort
- Algorithmic Implementation series(2)——Implementation of Selection_sort
- Algorithmic Implementation series(4) Implementation of Maximum Subarray problem(O(nlgn) and O(n))
- Implementation
- implementation
- Implementation of Polymorphism
- implementation of bitmap
- Implementation of Heap Sort
- The Implementation of ALG_DES_MAC8_ISO9797_1_M2_ALG3
- Implementation of CServer
- Implementation of CClient
- Implementation Of Choreography
- MATLAB Implementation of MonoSLAM
- Class文件内容及常量池
- Mysql的备份和恢复
- Algorithmic Implementation series(2)——Implementation of Selection_sort
- Java 虚拟机体系结构
- 理解Linux中的CPU负载
- Algorithmic Implementation series(3) Implementation of Merge_Sort
- 几个容易混淆的重定向
- java socket 多线程网络传输多个文件
- 阿里实习面试经历
- c#.net 内存中 动态创建类型以及程序集
- 十大OpenGL教程
- Cordova/Phonegap 升级至 2.8.0
- ml64.exe完整命令行参数解释
- 由调用方或被调用方保存的寄存器