Javascript: Merge Sort Implementation

Merge sort works by divide the unsorted list into n sublists, where n is the number of elements in the list. That being said it divides the list into n lists and each only contain one element. One element is considered sorted, thus we get n sorted lists. With the n sorted lists, then repeatedly merge them to produce new sublists until there is only 1 list remaining and that will be the sorted list.
Here is an example of merge sort using Javascript
[code language=”javascript”]
function mergeSort(data)
{
if(data.length == 1 ) return data;

var mid = data.length / 2;
var left = data.slice(0, mid);
var right = data.slice(mid);

left = mergeSort(left);
right = mergeSort(right);

return merge(left, right);
}

function merge(left, right)
{
var result=[];
var leftIndex=0;
var rightIndex=0;

while(leftIndex<left.length && rightIndex<right.length)
{
if(left[leftIndex]>right[rightIndex])
{

result.push(right[rightIndex]);
rightIndex++;
}
else
{
result.push(left[leftIndex]);
leftIndex++;
}
}
while(leftIndex<left.length)
{
result.push(left[leftIndex]);
leftIndex++;
}
while(rightIndex<right.length)
{
result.push(right[rightIndex]);
rightIndex++;
}
return result;
}
[/code]

Search within Codexpedia

Custom Search

Search the entire web

Custom Search