javascript希爾排序演算法程式碼例項

antzone發表於2017-04-11

本章節分享一段使用javascript實現的希爾排序演算法程式碼例項。

關於此演算法的具體實現原理,大家可以自行在網上查詢,介紹有很多。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<script type="text/javascript">
var array = new Array(12, 25, 32, 16, 18, 27, 59, 69, 36);
function shellSort(array) {
  var j, i, v, h = 1, s = 3, k, n = array.length;
  var result = "";
  var count = 0;
  while (h < n) {
    h = s * h + 1;
  }
     
  while(h > 1) {
    h=(h-1)/s;
    for (k=0; k<h; k++){
      for (i=k+h,j=i; i<n; i+=h, j=i) {
        v=array[i];
        while (true) {
          if ((j -= h) >= 0 && array[j] > v) {
            array[j + h] = array[j];
          }
          else {
            break;
          }
        }                
        array[j+h]=v;
      }
    }
    count++;
    result += "<br />第" + count + "遍排序的結果是:";
    for (var n = 0; n < array.length; n++) {
      result += array[n] + ",";
    }
  }
  return result;
}
window.onload = function () {
  var obox = document.getElementById("box");
  obox.innerHTML = shellSort(array)
}
</script>
</head>
<body>
<div id="box"></div>
</body>
</html>

相關文章