js 简单快排实现

来源:互联网 发布:win10该下载哪种mysql 编辑:程序博客网 时间:2024/05/18 09:19
<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Title</title></head><body><div style="width: 940px; margin: auto;">  <h4 id="original"></h4>  <ol id="result"></ol>  <button onclick="quick();">快排</button></div><script>  function quick() {    var a = [1,2,3,4,5,6,7,8,9,10], html = "", cnt = 0;    for( var i = 0; i < 10; i++ ) {      a[i] = randomNum(0, 100);    }    document.getElementById("original").innerText = "随机10位数组:" + a.toString().replace(/,/g, ', ');    function randomNum(min, max) {      return min + Math.floor( Math.random() * (max-min) );    }    function quickSort(a, b, e) {      if( e - b <= 1) return;      var m = randomNum(b, e);      var i = b, j = b + 1;      var tmp = a[i];      a[i] = a[m];      a[m] = tmp;      html += '<li><ol><li>第 ' + (i+1) + '(' + tmp + ')' + ' 与第 ' + (m+1) + '(' + a[i] + ')' + ' 交换,结果' + a.slice(b, e).toString().replace(/,/g, ', ') + '</li>';      while( i < e && j < e ) {        console.log(++cnt);        if( a[b] <= a[j] ) {          j++;        }        if( a[b] > a[j] ) {          tmp = a[j];          a[j++] = a[++i];          a[i] = tmp;          html += '<li>第 ' + (j) + '(' + tmp + ')' + ' 与第 ' + (i+1) + '(' + a[j-1] + ')' + ' 交换,结果' + a.slice(b, e).toString().replace(/,/g, ', ') + '</li>';        }      }      tmp = a[b];      a[b] = a[i];      a[i] = tmp;      html += '<li>第 ' + (b+1) + '(' + tmp + ')' + ' (随机数a['+ m + ']=' + tmp + ')与第 ' + (i+1) + '(' + a[b] + ')' + ' 交换,结果:' +  a.slice(b, e).toString().replace(/,/g, ', ')+'</li></ol></li>';      quickSort(a, b, i);      quickSort(a, i+1, e);    }    quickSort(a, 0, a.length);    document.getElementById("result").innerHTML = html;    console.log(a.toString());  }</script></body></html>

效果截图

0 0
原创粉丝点击