In this answer, I have shared how to implement merge sort in JavaScript.
Example: Merge sort in JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | <html> <body> <script> function mSort (array) { if (array.length === 1) { return array } const middle = Math.floor(array.length / 2) const left = array.slice(0, middle) const right = array.slice(middle) document.write(middle); return merge( mSort(left), mSort(right) ) } // compare the arrays item by item and return the concatenated result function merge (left, right) { let result = [] let leftIndex = 0 let rightIndex = 0 while (leftIndex < left.length && rightIndex < right.length) { if (left[leftIndex] < right[rightIndex]) { result.push(left[leftIndex]) leftIndex++ document.write("</br>"); } else { result.push(right[rightIndex]) rightIndex++ } } return result.concat(left.slice(leftIndex)).concat(right.slice(rightIndex)) } const list = [4,7,5,9,1,3,8,2] document.write(mSort(list)); </script> </body> </html> |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.