<script type="text/javascript">
//格式化時(shí)間
/**
* 格式化時(shí)間<br />
* eg: new Date().format('yyyy-MM-dd HH:mm:ss')//2009-10-19 16:21:30
*/
Date.prototype.format = function(format) {
var o = {
"M+" :this.getMonth() + 1, // month
"d+" :this.getDate(), // day
"H+" :this.getHours(), // hour
"m+" :this.getMinutes(), // minute
"s+" :this.getSeconds(), // second
"q+" :Math.floor((this.getMonth() + 3) / 3), // quarter
"S" :this.getMilliseconds()
// millisecond
}
if (/(y+)/.test(format))
format = format.replace(RegExp.$1, (this.getFullYear() + "")
.substr(4 - RegExp.$1.length));
for ( var k in o)
if (new RegExp("(" + k + ")").test(format))
format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k]
: ("00" + o[k]).substr(("" + o[k]).length));
return format;
}
var arr = new Array(5, 2, 4, 6, 1, 3);
document.write("插入排序法:");
document.write("<br />" + new Date().format('yyyy-MM-dd HH:mm:ss.S'));
document.write("<br />排序前:" + arr.join(", "));
document.write("<br />排序后:" + InsertionSort(arr));
document.write("<br />" + new Date().format('yyyy-MM-dd HH:mm:ss.S'));
//插入排序法
function InsertionSort(arr)
{
//******核心部分開始************************************
for(var i=1; i<arr.length; i++)
{
var key = arr[i];//關(guān)鍵字,從序列的第2個(gè)元素開始。
var j = i - 1;//關(guān)鍵字元素的前一個(gè)元素索引值。從零開始。
//遍歷關(guān)鍵字前的序列,從后向前逐個(gè)與關(guān)鍵字比較,如果大于關(guān)鍵字,就向后移一位。
while(j >= 0 && key < arr[j])
{
arr[j+1] = arr[j];//把比關(guān)鍵字大的元素,
j--;//從后向前遍歷,所以減減。
}
//經(jīng)過上一個(gè)循環(huán)比較后,j當(dāng)前指的元素是小于關(guān)鍵字的。
//所以關(guān)鍵字應(yīng)放置在j+1位置。
arr[j+1] = key;
}
//******核心部分結(jié)束************************************
return arr.join(", ");//返回字符串值,其中包含了連接到一起的數(shù)組的所有元素,元素由指定的分隔符分隔開來(lái)。
}
</script>