Skip to content

Commit 5e1d137

Browse files
authored
Merge pull request larissalages#258 from ALaurinne/3-merge-sort
Add Merge Sort in Dart.
2 parents 6ea6766 + efcee7a commit 5e1d137

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
void merge(List list, int leftIndex, int middleIndex, int rightIndex) {
2+
int leftSize = middleIndex - leftIndex + 1;
3+
int rightSize = rightIndex - middleIndex;
4+
5+
List leftList = List(leftSize);
6+
List rightList = List(rightSize);
7+
8+
for (int i = 0; i < leftSize; i++) leftList[i] = list[leftIndex + i];
9+
for (int j = 0; j < rightSize; j++) rightList[j] = list[middleIndex + j + 1];
10+
11+
int i = 0, j = 0;
12+
int k = leftIndex;
13+
14+
while (i < leftSize && j < rightSize) {
15+
if (leftList[i] <= rightList[j]) {
16+
list[k] = leftList[i];
17+
i++;
18+
} else {
19+
list[k] = rightList[j];
20+
j++;
21+
}
22+
k++;
23+
}
24+
25+
while (i < leftSize) {
26+
list[k] = leftList[i];
27+
i++;
28+
k++;
29+
}
30+
31+
while (j < rightSize) {
32+
list[k] = rightList[j];
33+
j++;
34+
k++;
35+
}
36+
}
37+
38+
void mergeSort(List list, int leftIndex, int rightIndex) {
39+
if (leftIndex < rightIndex) {
40+
int middleIndex = (rightIndex + leftIndex) ~/ 2;
41+
42+
mergeSort(list, leftIndex, middleIndex);
43+
mergeSort(list, middleIndex + 1, rightIndex);
44+
45+
merge(list, leftIndex, middleIndex, rightIndex);
46+
}
47+
}

readme.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ Code | Test
3737
[Bubble Sort](https://github.com/larissalages/code_problems/blob/master/classical_algorithms/dart/BubbleSort.dart) | Missing tests
3838
[Quick Sort](https://github.com/larissalages/code_problems/blob/master/classical_algorithms/dart/QuickSort.dart) | Missing tests
3939
[Binary Sort](https://github.com/larissalages/code_problems/blob/master/classical_algorithms/dart/BinarySort.dart) | Missing tests
40+
[Merge Sort](https://github.com/larissalages/code_problems/blob/master/classical_algorithms/java/MergeSort.dart) | Missing tests
4041

4142
### C++
4243
Code | Test

0 commit comments

Comments
 (0)