js实现归并排序

时间:2021-08-30 16:29:02
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);

归并排序要点

1.将要排序的数组递归的进行切分为start,middle,end三部分

2.将排好序的start-middle与middle-end合并为一个数组

function merge_sort(arr){
_sort_merge(arr, arr, 0, arr.length -1);
} function _sort_merge(src, desc, start, end){
var tmp_arr = [];
if(start == end){
desc[start] = src[start];
}else{
var m = parseInt((start + end)/2);
_sort_merge(src, tmp_arr, start, m);
_sort_merge(src, tmp_arr, m + 1, end);
merge(tmp_arr, desc, start, m, end);
}
} function merge(src, desc, start, m, end){
var i = start,j = m + 1, index = start;
while(i <= m && j <= end){
if(src[i] > src[j]){
desc[index] = src[i];
index++;
i++;
}else{
desc[index] = src[j];
index++;
j++;
}
}
while(i <= m){
desc[index] = src[i];
index++;
i++;
}
while( j <= end){
desc[index] = src[j];
index++;
j++;
}
}
var arr = [22, 31, 1, 9, 99, 68, 55, 30];
merge_sort(arr);
console.log(arr);