Site Search:

try out javascript for merge sort



0
1
2
3
4
5
6
7
8
9
function merge(a, lo, mid, hi) {  
  // Merge a[lo..mid] with a[mid+1..hi].
  var i = lo; 
  var j = mid+1;
  for (var k = lo; k <= hi; k++) { 
    // Copy a[lo..hi] to aux[lo..hi].
    aux[k] = a[k];
  }
  for (var k = lo; k <= hi; k++) { 
    // Merge back to a[lo..hi].
    if      (i > mid)              a[k] = aux[j++];
    else if (j > hi )              a[k] = aux[i++];
    else if (aux[j] < aux[i])      a[k] = aux[j++];
    else                           a[k] = aux[i++];
  }
}

function sort_m(a) {
  mergeSort(a, 0, a.length - 1);
}

function mergeSort(a, lo, hi) {  
  // Sort a[lo..hi].
  alert('lo = ' + lo + ', hi = ' + hi);
  if (hi <= lo) {
    return;
  }
  var mid = lo + Math.floor((hi - lo)/2);
  mergeSort(a, lo, mid);       // Sort left half.
  mergeSort(a, mid+1, hi);     // Sort right half.
  merge(a, lo, mid, hi); 
  alert(a);
}