1+ import 'ArrayGenerator.dart' ;
2+
3+ /**
4+ * 归并排序
5+ */
6+ class MergeSort {
7+
8+ static sort (List arr){
9+ _sortContent (arr,0 ,arr.length- 1 );
10+ }
11+
12+ static _sortContent (List arr,int left,int right){
13+ if (left >= right){
14+ return ;
15+ }
16+ int mid = ((right- left)/ 2 ).toInt () + left;
17+ _sortContent (arr, left, mid);
18+ _sortContent (arr, mid+ 1 , right);
19+ _merge (arr,left,mid,right);
20+ }
21+
22+ static _merge (List arr,int l,int mid,int right){
23+ // List temp = List.copyRange(arr, l, r!+1);
24+ List temp = List .filled (right+ 1 - l, true );
25+ List .copyRange (temp, 0 , arr,l,right+ 1 );
26+ int i = l, j = mid + 1 ;
27+
28+ // 每轮循环为 arr[k] 赋值
29+ for (int k = l; k <= right; k ++ ){
30+ if (i > mid){
31+ arr[k] = temp[j - l]; j ++ ;
32+ }
33+ else if (j > right){
34+ arr[k] = temp[i - l]; i ++ ;
35+ }
36+ else if (temp[i - l].compareTo (temp[j - l]) <= 0 ){
37+ arr[k] = temp[i - l]; i ++ ;
38+ }
39+ else {
40+ arr[k] = temp[j - l]; j ++ ;
41+ }
42+ }
43+ }
44+ }
45+ void main (){
46+ int n = 100 ;
47+ List arr = ArrayGenerator .generateRandomArray (n, n);
48+ MergeSort .sort (arr);
49+ print (arr);
50+ }
0 commit comments