七大排序之归并排序

Posted jibisheng

tags:

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

 1 #include<iostream>
 2 #include<time.h>
 3 #include<stdlib.h>
 4 #include<sys/timeb.h>
 5 using namespace std;
 6 
 7 const int Max = 9999;
 8 
 9 void swap(int& a, int& b) {
10     int temp = a;
11     a = b;
12     b = temp;
13 }
14 
15 
16 long getSystemTime() {
17     struct timeb tb;
18     ftime(&tb);
19     return tb.time * 1000 + tb.millitm;
20 }
21 void Print(const int* arr, int length) {
22     for (int i = 0; i < length; i++) {
23         cout << arr[i] << " ";
24     }
25 
26 }
27 void Merge(int* arr,int start,int end,int mid,int* temp) {
28     int i_start = start;
29     int i_end = mid;
30     int j_start = mid + 1;
31     int j_end = end;
32     int length = 0;
33     while (i_start <= i_end && j_start <= j_end) {
34         if (arr[i_start] < arr[j_start]) {
35             temp[length] = arr[i_start];
36             length++;
37             i_start++;
38         }
39         else
40         {
41             temp[length] = arr[j_start];
42             length++;
43             j_start++;
44         }
45     }
46     while (i_start<=i_end)
47     {
48         temp[length] = arr[i_start];
49         length++;
50         i_start++;
51     }
52     while (j_start <= j_end)
53     {
54         temp[length] = arr[j_start];
55         length++;
56         j_start++;
57     }
58     for (int i = 0; i < length; i++) {
59         arr[start+i] = temp[i];//注意是不是arr[i]
60     }
61 }
62 void MergeSort(int* arr, int start, int end, int* temp) {
63     if (start == end) return;
64     int mid = (start + end) / 2;
65     MergeSort(arr, start, mid,temp);
66     MergeSort(arr, mid + 1, end, temp);
67 
68     Merge(arr, start, end, mid, temp);
69 }
70 
71 int main() {
72     int arr[Max];
73     int tmp[Max];
74     srand((unsigned)time(NULL));
75     for (int i = 0; i < Max; i++) {
76         arr[i] = rand() % Max;
77     }
78     //cout << "排序前:
";
79     //Print(arr, Max);
80     long pt = getSystemTime();
81     MergeSort(arr,0,Max-1,tmp);
82     long at = getSystemTime();
83     //cout << "
排序后:
";
84     //Print(arr, Max);
85 
86     cout << "
time of sort:" << at - pt << "ms
";
87 
88 
89     return 0;
90 }

 

以上是关于七大排序之归并排序的主要内容,如果未能解决你的问题,请参考以下文章

C/C++ 七大排序算法 之 “归并排序”

java七大排序——7_归并排序

七大排序算法(插排,希尔,选择排序,堆排,冒泡,快排,归并)--图文详解

数据结构图解七大排序

C/C++ 七大排序算法 之 “快速排序”

七大排序算法分析及java实现