码迷,mamicode.com
首页 > 编程语言 > 详细

七大排序之归并排序

时间:2020-06-01 20:36:38      阅读:63      评论:0      收藏:0      [点我收藏+]

标签:start   mergesort   nbsp   gets   rand   int   pre   long   ++   

 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 << "排序前:\n";
79     //Print(arr, Max);
80     long pt = getSystemTime();
81     MergeSort(arr,0,Max-1,tmp);
82     long at = getSystemTime();
83     //cout << "\n排序后:\n";
84     //Print(arr, Max);
85 
86     cout << "\ntime of sort:" << at - pt << "ms\n";
87 
88 
89     return 0;
90 }

 

七大排序之归并排序

标签:start   mergesort   nbsp   gets   rand   int   pre   long   ++   

原文地址:https://www.cnblogs.com/jibisheng/p/13027221.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!