七大排序之归并排序
标签:start mergesort nbsp gets rand int pre long ++
1 #include 2 #include 3 #include 4 #include 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 ) {
23 cout " ";
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 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_starti_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 ) {
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 ) {
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 "\ntime of sort:" "ms\n";
87
88
89 return 0;
90 }
七大排序之归并排序
标签:start mergesort nbsp gets rand int pre long ++
原文地址:https://www.cnblogs.com/jibisheng/p/13027221.html
文章来自:
搜素材网的
编程语言模块,转载请注明文章出处。
文章标题:
七大排序之归并排序
文章链接:http://soscw.com/index.php/essay/38898.html
评论