各种排序总结(六)归并排序
生活随笔
收集整理的這篇文章主要介紹了
各种排序总结(六)归并排序
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1 /****************
2 思路:假設待排序有n個記錄,將這n個記錄看成n個有序的子序列,每個子序列長度為1,
3 然后兩兩歸并。
4 如何將將二個有序數列合并:這個非常簡單,只要從比較二個數列的第一個數,
5 誰小就先取誰,取了后就在對應數列中刪除這個數。然后再進行比較,如果有數列為空,
6 那直接將另一個數列的數據依次取出即可。
7 ****************/
8 #include <iostream>
9
10 using namespace std;
11
12 //將有二個有序數列arr[first...mid]和arr[mid...last]合并。主要是merge這個函數
13 void Merge(int* arr, int first, int mid, int last, int* temp)
14 {
15 int f1 = first;
16 int m = mid;
17 int f2 = mid+1;
18 int l = last;
19 int i = 0;
20 while((f1 <= m)&&(f2 <= l))
21 {
22 if(arr[f1] < arr[f2])
23 temp[i++] = arr[f1++];
24 else
25 temp[i++] = arr[f2++];
26 }
27 while(f1 <= m)
28 temp[i++] = arr[f1++];
29 while(f2 <= l)
30 temp[i++] = arr[f2++];
31 for(int j=0; j<i; j++)
32 arr[first + j] = temp[j];
33 }
34
35
36 void MergeSort(int* arr, int first, int last, int* temp)
37 {
38 int mid;
39 if(first < last) //if first >= last, return
40 {
41 mid = (first + last) /2;
42 MergeSort(arr, first, mid, temp);
43 MergeSort(arr, mid+1, last, temp);
44 Merge(arr,first, mid, last, temp);
45 }
46 }
47
48
49 int main()
50 {
51 int * arr;
52 int * temp;
53 int n;
54 cout<<"Input the arr length:"<<endl;
55 cin>>n;
56 arr = new int[n];
57 temp = new int[n];
58 cout<<"Input the arr elements:"<<endl;
59 for(int i=0;i<n;i++)
60 {
61 cin>>arr[i];
62 }
63 MergeSort(arr,0,n-1,temp);
64 cout<<"The outcome:"<<endl;
65 for(int i=0;i<n;i++)
66 cout<<arr[i]<<endl;
67 return 0;
68 }
69 /************************
70 穩定的。
71 時間復雜度:歸并排序不依賴與原始數組的輸入情況,每次劃分時兩個子序列長度都是基本一樣的,
72 因此最大、最小和平均時間均為O(nlogn)。
73 空間復雜度:用到一個臨時數組,因此空間代價為O(n)。
74 總結:
75 1.排序時間不依賴于原始數組;
76 2.時間為O(nlogn),因此適用于數組n較大的情況;
77 3.空間代價為O(n)。
78 *************************/
?
轉載于:https://www.cnblogs.com/CnZyy/p/3314705.html
總結
以上是生活随笔為你收集整理的各种排序总结(六)归并排序的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 链表二路归并
- 下一篇: 每日记载内容总结22