您的位置:首页 > 编程语言 > Go语言

Algorithmic Implementation series(3) Implementation of Merge_Sort

2013-06-10 21:24 477 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: