鎻掑叆鎺掑簭浠g爜鍒嗘瀽
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了鎻掑叆鎺掑簭浠g爜鍒嗘瀽相关的知识,希望对你有一定的参考价值。
鏍囩锛?a href='http://www.mamicode.com/so/1/%e6%8e%92%e5%ba%8f%e7%ae%97%e6%b3%95' title='鎺掑簭绠楁硶'>鎺掑簭绠楁硶 mat return asc span bsp 鐩存帴鎻掑叆 姣旇緝 fun
鐩存帴鎻掑叆鎺掑簭 JavaScript 瀹炵幇浠g爜锛?/h3>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
function insertionSort(array) {
//鑷畾涔夊嚱鏁帮紝浜ゆ崲i鍜宩鐨勪綅缃?/span>
function swap(array, i, j) {
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
var length = array.length,
i,//浠庣浜岄」寮€濮嬶紝涓庡墠涓€椤逛綔姣旇緝
j;//涓轰簡寰€鍓嶈繘琛屾瘮杈?/span>
for (i = 1; i < length; i++) {
for (j = i; j > 0; j--) {
//浠庣j椤瑰紑濮嬶紝涓庡墠涓€椤规瘮杈冨ぇ灏忥紝濡傛灉鍓嶉」澶т簬鍚庨」锛屽垯浜ゆ崲浣嶇疆锛涘鏋滃墠椤瑰皬浜庣瓑浜庡悗椤癸紝璇存槑褰撳墠鎺掑簭瀹屾垚锛岃烦鍑哄綋鍓嶅惊鐜紝i++杩涜涓嬩竴椤规瘮杈冿紝鐩村埌鏈€鍚庝竴椤广€?/span>
if (array[j - 1] > array[j]) {
swap(array, j - 1, j);
} else {
break;
}
}
}
return array;
}
鐩存帴鎻掑叆鎺掑簭 javascript 瀹炵幇浠g爜锛屽噺灏戜氦鎹㈡鏁帮細
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function insertionSort(array) {
var length = array.length,
i,
j,
temp;//涓轰簡涓存椂淇濆瓨arr[i]
for (i = 1; i < length; i++) {
temp = array[i];//鍥犱负濡傛灉鍓嶄竴椤规瘮鍚庝竴椤瑰ぇ锛屽垯鍓嶄竴椤硅绉诲埌鍚庝竴椤癸紝浼氳鐩栫椤圭殑鍊硷紝鐩村埌绗琷椤规椂锛宩-1灏忎簬绛変簬绗琷椤癸紝璇存槑涔嬪墠绗琲椤圭殑椤哄簭鍦ㄧj椤?/span>
for (j = i; j >= 0; j--) {
if (array[j - 1] > temp) {
array[j] = array[j - 1];
} else {
array[j] = temp;
break;
}
}
}
return array;
}
鐩存帴鎻掑叆鎺掑簭 JavaScript 瀹炵幇浠g爜锛屼簩鍒嗘煡鎵炬帓搴?/h3>
澶т笓鏍?/a> 鎻掑叆鎺掑簭浠g爜鍒嗘瀽class="gutter">1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
function insertionSort2(array) {
function binarySearch(array, start, end, temp) {
var middle;
while (start <= end) {
//鍚戜笅鍙栨暣锛岃幏寰椾腑闂寸殑鍧愭爣
middle = Math.floor((start + end) / 2);
if (array[middle] < temp) {//璇存槑temp鍦╩iddle鍧愭爣鍚?/span>
if (temp <= array[middle + 1]) {//璇存槑绗琺iddle+1椤瑰垰澶т簬middle椤癸紝杩斿洖middle+1
return middle + 1;
} else {
//鑼冨洿鍑?锛屽啀娆¤繘琛寃hile寰幆锛岀洿鍒版壘鍒皌emp椤哄簭浣嶇疆
start = middle + 1;
}
} else {//璇存槑temp鐨勯『搴忎綅缃湪middle涔嬪墠
if (end === 0) {//浣跨敤==鐨勯兘浣跨敤===
//璇存槑temp鏈€灏?/span>
return 0;
} else {
//浠?-middle寮€濮嬫壘
end = middle;
}
}
}
}
function binarySort(array) {
var length = array.length,
i,
j,
k,
temp;
for (i = 1; i < length; i++) {
temp = array[i];
if (array[i - 1] <= temp) {
//鍓嶄竴椤瑰垰濂藉皬浜庣瓑浜庣i椤癸紝涓嶇敤鍐嶈繘琛屾帓搴?/span>
k = i;
} else {
//杩涜浜屽垎鏌ユ壘
k = binarySearch(array, 0, i - 1, temp);
//鎵惧埌temp鐨勫潗鏍噆锛屽皢鍧愭爣鍚庣殑閮藉線鍚庣Щ涓€浣?/span>
for (j = i; j > k; j--) {
array[j] = array[j - 1];
}
}
array[k] = temp;
}
return array;
}
return binarySort(array);
}
寮曠敤
1 |
|
1 |
|
澶т笓鏍?/a> 鎻掑叆鎺掑簭浠g爜鍒嗘瀽class="gutter">1 |
|
寮曠敤
以上是关于鎻掑叆鎺掑簭浠g爜鍒嗘瀽的主要内容,如果未能解决你的问题,请参考以下文章