1+ import 'ArrayGenerator.dart' ;
2+ import 'dart:math' ;
3+
4+ /**
5+ * 自底向上归并排序
6+ */
7+ class MergeSort {
8+
9+ static sort (List arr){
10+ _sortContent (arr,0 ,arr.length- 1 );
11+ }
12+
13+ static sortBU (List arr){
14+ List temp = List .filled (arr.length, true );
15+ List .copyRange (temp,0 ,arr);
16+ int n = arr.length;
17+ // 遍历合并的区间长度
18+ for (int sz = 1 ; sz < n; sz += sz){
19+ // 遍历合并的两个区间的起始位置 i
20+ // 合并 [i, i + sz - 1] 和 [i + sz, Math.min(i + sz + sz - 1, n - 1)]
21+ for (int i = 0 ; i + sz < n; i += sz + sz)
22+ if (arr[i + sz - 1 ].compareTo (arr[i + sz]) > 0 )
23+ _merge2 (arr, i, i + sz - 1 , [i + sz + sz - 1 , n - 1 ].reduce (min), temp);
24+ }
25+ }
26+
27+ static sort2 (List arr){
28+ List temp = List .filled (arr.length, true );
29+ List .copyRange (temp,0 ,arr);
30+ _sortContent2 (arr, 0 , arr.length - 1 , temp);
31+ }
32+
33+ static _sortContent2 (List arr,int left,int right,List temp){
34+ if (left >= right)
35+ return ;
36+
37+ int mid = ((right - left) / 2 ).toInt () + left;
38+ _sortContent2 (arr, left, mid, temp);
39+ _sortContent2 (arr, mid + 1 , right, temp);
40+
41+ if (arr[mid].compareTo (arr[mid + 1 ]) > 0 )
42+ _merge2 (arr, left, mid, right, temp);
43+ }
44+ static _merge2 (List arr,int left,int mid,int right,List temp){
45+ List .copyRange (temp, left, arr,left,right+ 1 );
46+ int i = left, j = mid + 1 ;
47+
48+ // 每轮循环为 arr[k] 赋值
49+ for (int k = left; k <= right; k ++ ){
50+ if (i > mid){
51+ arr[k] = temp[j];
52+ j ++ ;
53+ }
54+ else if (j > right){
55+ arr[k] = temp[i];
56+ i ++ ;
57+ }
58+ else if (temp[i].compareTo (temp[j]) <= 0 ){
59+ arr[k] = temp[i];
60+ i ++ ;
61+ }
62+ else {
63+ arr[k] = temp[j];
64+ j ++ ;
65+ }
66+ }
67+ }
68+
69+
70+
71+ static _sortContent (List arr,int left,int right){
72+ /**
73+ * 当数组过小时,可以使用插入排序
74+ */
75+ if (left >= right){
76+ return ;
77+ }
78+ int mid = ((right- left)/ 2 ).toInt () + left;
79+ _sortContent (arr, left, mid);
80+ _sortContent (arr, mid+ 1 , right);
81+ //提前进行判断,少一步merge
82+ if (arr[mid].compareTo (arr[mid+ 1 ])> 0 ){
83+ _merge (arr,left,mid,right);
84+ }
85+ }
86+
87+ static _merge (List arr,int l,int mid,int right){
88+ List temp = List .filled (right+ 1 - l, true );
89+ List .copyRange (temp, 0 , arr,l,right+ 1 );
90+ int i = l, j = mid + 1 ;
91+
92+ // 每轮循环为 arr[k] 赋值
93+ for (int k = l; k <= right; k ++ ){
94+ if (i > mid){
95+ arr[k] = temp[j - l]; j ++ ;
96+ }
97+ else if (j > right){
98+ arr[k] = temp[i - l]; i ++ ;
99+ }
100+ else if (temp[i - l].compareTo (temp[j - l]) <= 0 ){
101+ arr[k] = temp[i - l]; i ++ ;
102+ }
103+ else {
104+ arr[k] = temp[j - l]; j ++ ;
105+ }
106+ }
107+ }
108+ }
109+ void main (){
110+ int n = 100 ;
111+ // List arr = ArrayGenerator.generateRandomArray(n, n);
112+ // MergeSort.sort(arr);
113+ // print(arr);
114+ List arr2 = ArrayGenerator .generateRandomArray (n, n);
115+ print (arr2);
116+ MergeSort .sortBU (arr2);
117+ print (arr2);
118+ }
0 commit comments