Merge-Sort
Merge sort is an example of a divide-and-conquer type sorting-algorithm.The input of merge sort is an array of some elements, which are need to be arranged typically from least to the greatest.
Steps to follow in Merge Sort
- Merge sort divides the array in to two sub arrays and later divides each array in to another two arrays and so on until a bunch of single element arrays are left. For instance, in the following example the array [4,7,5,9,1,3,8,2] divides in to single array elements such as [4], [7], [5], [9], [1], [3], [8], [2].
- It starts comparing arrays in such a manner that two arrays are compared and concatenated. In the following example, it compares two arrays at a time that is [4], [7] are compared and concatenated then [5], [9] are compared and concatenated and so on such that arrays [4,7], [5,9], [1,3], [2,8] are formed.
- It follows the same way that is two-two arrays are compared and concatenated to form two arrays. In the following example [4,7] and [5,9] are compared and concatenated to get an array as [4,5,7,9] and same is the case with other two arrays to form an array as [1,2,3,8].
- Same rule applicable here that is the remaining two arrays compares and concatenates to get a final array as [1,2,3,4,5,7,8,9].
Example
<html>
<body>
<script>
function mSort (array) {
if (array.length === 1) {
return array // return once we hit an array with a single item
}
const middle = Math.floor(array.length / 2) // get the middle item of the array rounded down
const left = array.slice(0, middle) // items on the left side
const right = array.slice(middle) // items on the right side
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>Output
1,2,3,4,5,7,8,9