Skip to content

Commit 2722dca

Browse files
committed
refactored merged sort a little
1 parent 4145ec6 commit 2722dca

File tree

1 file changed

+14
-20
lines changed

1 file changed

+14
-20
lines changed

src/_.general/sorting.js

Lines changed: 14 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -218,30 +218,25 @@ export function quickSort(array, lo, hi) {
218218
export function mergeSort(array) {
219219
const arr = array.slice();
220220
checkArray(arr);
221-
if (arr.length < 2) {
222-
return arr;
223-
}
224-
const merge = (a, b) => {
221+
if (arr.length < 2) return arr;
222+
223+
const merge = (left, right) => {
225224
const result = [];
226-
const lenA = a.length;
227-
const lenB = b.length;
228225
let i = 0;
229226
let j = 0;
230-
while (i < lenA && j < lenB) {
231-
if (a[i] === b[j]) {
232-
result.push(a[i], b[j]);
227+
while (i < left.length && j < right.length) {
228+
if (left[i] <= right[j]) {
229+
result.push(left[i]);
233230
i += 1;
231+
}
232+
if (left[i] >= right[j]) {
233+
result.push(right[j]);
234234
j += 1;
235-
} else if (a[i] > b[j]) {
236-
result.push(b[j]);
237-
j += 1;
238-
} else {
239-
result.push(a[i]);
240-
i += 1;
241235
}
242236
}
243-
return result.concat(a.slice(i), b.slice(j));
237+
return result.concat(left.slice(i), right.slice(j));
244238
};
239+
245240
const mid = Math.floor(arr.length / 2);
246241
return merge(mergeSort(arr.slice(0, mid)), mergeSort(arr.slice(mid)));
247242
}
@@ -264,9 +259,8 @@ export function mergeSort(array) {
264259
export function heapSort(array) {
265260
const arr = array.slice();
266261
checkArray(arr);
267-
if (arr.length < 2) {
268-
return arr;
269-
}
262+
if (arr.length < 2) return arr;
263+
270264
const heapify = (list, index, end = list.length - 1) => {
271265
const parentIndex = Math.ceil(index / 2) - 1;
272266
if (index < 0 || parentIndex < 0) {
@@ -289,4 +283,4 @@ export function heapSort(array) {
289283
}
290284

291285
return arr;
292-
}
286+
}

0 commit comments

Comments
 (0)