Skip to content

Commit 1814ea6

Browse files
author
tianqing.liang
committed
归并排序
1 parent f87f842 commit 1814ea6

File tree

3 files changed

+72
-0
lines changed

3 files changed

+72
-0
lines changed

07MergeSort/ArrayGenerator.dart

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import 'dart:math';
2+
3+
class ArrayGenerator{
4+
5+
static List generateOrderedArray(int n){
6+
List arr = List.filled(n, true);
7+
for(int i = 0;i<n;i++){
8+
arr[i] =i;
9+
}
10+
return arr;
11+
}
12+
13+
static List generateRandomArray(int n,int bound){
14+
List arr = List.filled(n, true);
15+
Random random = new Random();
16+
for(int i = 0; i < n; i ++){
17+
arr[i] = random.nextInt(bound);
18+
}
19+
return arr;
20+
}
21+
}

07MergeSort/MergeSort.dart

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
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+
}

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,4 +8,5 @@
88
4. 栈,队列,循环队列
99
5. 链表,链表实现栈,链表实现队列
1010
6. 递归
11+
7. 归并排序
1112

0 commit comments

Comments
 (0)