码迷,mamicode.com
首页 > 编程语言 > 详细

js实现归并排序

时间:2015-12-12 16:50:20      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:

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);

js实现归并排序

标签:

原文地址:http://www.cnblogs.com/fengfengtk/p/5041345.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!