function merge(s_arr, d_arr, start, middle, end){
var s_temp = start;
var m_temp = middle+1;
var temp;
var d = start;
for(;s_temp <= middle && m_temp <= end; d++){
if(s_arr[s_temp] < s_arr[m_temp]){
d_arr[d] = s_arr[s_temp];
s_temp++;
}else{
d_arr[d] = s_arr[m_temp];
m_temp++;
}
}
if(s_temp <= middle){
for(temp = 0;temp <= middle -s_temp; temp++){
d_arr[d + temp] = s_arr[s_temp + temp];
}
}
if(m_temp <= end){
for(temp = 0;temp <= end -m_temp; temp++){
d_arr[d+temp] = s_arr[m_temp + temp];
}
}
}
// var arr1 = [1, 4, 8, 10, 2, 5, 9, 11];
// var arr2 = [];
// merge(arr1, arr2, 0, 1, 2);
function merge_sort(arr){
sort_merge(arr, arr, 0, arr.length-1);
}
function sort_merge(s_arr, d_arr, start, end){
if(start == end){
d_arr[start] = s_arr[start];
}else{
var m = parseInt((start + end)/2);
//console.log(m);
sort_merge(s_arr, d_arr2, start, m);
sort_merge(s_arr, d_arr2, m + 1, end);
merge(d_arr2, d_arr,start, m, end);
}
}
merge_sort(arr)
console.log(arr);
原文:http://www.cnblogs.com/fengfengtk/p/5041345.html