Skip to content

Commit 5ef3f6c

Browse files
committed
Refactor the merge sort code with a single async function to add delay
1 parent 6cfa8ce commit 5ef3f6c

File tree

1 file changed

+15
-18
lines changed

1 file changed

+15
-18
lines changed

function.js

Lines changed: 15 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -155,8 +155,17 @@ const SortAlgo = {
155155
const timer = (ms) => new Promise((res) => setTimeout(res, ms));
156156

157157
// async function for selection sort algorithm
158-
async function sort(self) {
159-
function merge(arr, l, m, r) {
158+
async function sort(self, arr, l, r) {
159+
// l is for left index and r is
160+
// right index of the sub-array
161+
// of arr to be sorted */
162+
if (r > l) {
163+
var m = l + parseInt((r - l) / 2);
164+
165+
sort(this, arr, l, m);
166+
167+
sort(this, arr, m + 1, r);
168+
160169
var n1 = m - l + 1;
161170
var n2 = r - m;
162171

@@ -205,31 +214,19 @@ const SortAlgo = {
205214
j++;
206215
k++;
207216
}
217+
swapBar(data);
208218
}
209219

210-
// l is for left index and r is
211-
// right index of the sub-array
212-
// of arr to be sorted */
213-
function mergeSort(arr, l, r) {
214-
if (l >= r) {
215-
return; //returns recursively
216-
}
217-
var m = l + parseInt((r - l) / 2);
218-
mergeSort(arr, l, m);
219-
mergeSort(arr, m + 1, r);
220-
merge(arr, l, m, r);
221-
}
222-
mergeSort(data, 0, data.length - 1);
223-
swapBar(data);
224-
await timer(time);
220+
console.log(data);
225221
svg.selectAll("rect").style("fill", "#56b4d3");
226222
completeAudio.play();
227223
isSorting = false;
228224
isSorted = true;
229225
togglePlay();
230226
}
227+
231228
// calling sort function here
232-
sort(this);
229+
sort(this, data, 0, data.length - 1);
233230
},
234231

235232
// If user wants to stop the sorting process then this function will be called and sorting algorithm will be stopped immediately.

0 commit comments

Comments
 (0)