Skip to content

Commit 9dcb752

Browse files
committed
Refactoring
1 parent 8554de9 commit 9dcb752

File tree

1 file changed

+10
-22
lines changed

1 file changed

+10
-22
lines changed

src/main/scala/com/github/skozlov/algorithms/sort/MergeSort.scala

Lines changed: 10 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,7 @@ import scala.math.Ordered.orderingToOrdered
1515
* @see
1616
* [[https://en.wikipedia.org/wiki/Merge_sort]]
1717
*/
18-
class MergeSort[A] {
19-
import MergeSort._
20-
18+
class MergeSort[A](val smallChunkSize: Int, val smallChunkSort: FunctionalSort[A]) {
2119
// noinspection ScalaWeakerAccess
2220
@tailrec
2321
final def merge(
@@ -38,11 +36,10 @@ class MergeSort[A] {
3836
}
3937
}
4038

41-
def sortWithBuffers(
39+
def sort(
4240
input: Slice[A],
4341
primaryBuffer: WritableSlice[A],
4442
secondaryBuffer: WritableSlice[A],
45-
smallChunkSort: SmallChunkSort[A] = SmallChunkSort(chunkSize = 5, sort = InsertionSort[A]),
4643
)(implicit ordering: Ordering[A]): WritableSlice[A] = {
4744
require(
4845
primaryBuffer.size == input.size,
@@ -95,46 +92,37 @@ class MergeSort[A] {
9592
} else if (input.size == 1) {
9693
primaryBuffer(0) = input(0)
9794
primaryBuffer
98-
} else if (smallChunkSort.chunkSize <= 1) {
95+
} else if (smallChunkSize <= 1) {
9996
sort(input, primaryBuffer, secondaryBuffer, sortedChunkSize = 1)
10097
} else {
10198
val inChunks: Iterator[Slice[A]] =
102-
input.grouped(size = smallChunkSort.chunkSize)
99+
input.grouped(size = smallChunkSize)
103100
val outChunks: Iterator[WritableSlice[A]] =
104-
primaryBuffer.grouped(size = smallChunkSort.chunkSize)
101+
primaryBuffer.grouped(size = smallChunkSize)
105102
for ((in, out) <- inChunks zip outChunks) {
106-
smallChunkSort.sort.sortFunctionally(in, out)
103+
smallChunkSort.sortFunctionally(in, out)
107104
}
108-
if (smallChunkSort.chunkSize >= input.size) {
105+
if (smallChunkSize >= input.size) {
109106
primaryBuffer
110107
} else {
111108
sort(
112109
input = primaryBuffer,
113110
primaryBuffer = secondaryBuffer,
114111
secondaryBuffer = primaryBuffer,
115-
sortedChunkSize = smallChunkSort.chunkSize,
112+
sortedChunkSize = smallChunkSize,
116113
)
117114
}
118115
}
119116
}
120117

121-
def sortWithBuffer(
118+
def sort(
122119
input: WritableSlice[A],
123120
buffer: WritableSlice[A],
124-
smallChunkSort: SmallChunkSort[A] =
125-
SmallChunkSort(chunkSize = 5, sort = InsertionSort[A]),
126121
)(implicit ordering: Ordering[A]): WritableSlice[A] = {
127-
sortWithBuffers(
122+
sort(
128123
input = input,
129124
primaryBuffer = buffer,
130125
secondaryBuffer = input,
131-
smallChunkSort = smallChunkSort,
132126
)
133127
}
134128
}
135-
136-
object MergeSort {
137-
class SmallChunkSort[A](val chunkSize: Int, val sort: FunctionalSort[A]) {
138-
require(chunkSize >= 0, "Negative chunk size: " + chunkSize)
139-
}
140-
}

0 commit comments

Comments
 (0)