Javascript实现排序(5种)、二分查找、二叉树查找算法
<script type="text/javascript">
var a;
a = [66, 53, 11, 5, 4, 3, 2, 1];
/*冒泡排序*/
(function maopaopaixu() {
for (var i = 0; i < a.length - 1; i++) {//比较的次数是length-1
for (var j = 0; j < a.length - 1 - i; j++) {
if (a[j] > a[j + 1]) {
[a[j],a[j + 1]] = [a[j + 1],a[j]];
}
}
}
console.log(a);
})();
a = [66, 53, 11, 5, 4, 3, 2, 1];
/*选择排序*/
(function xuanzepaixu() {
var min/*最小项的索引*/, tmp;
for (var out = 0; out < a.length - 1; out++) {//比较的次数是length-1
min = out;
for (var inner = out + 1; inner < a.length; inner++) {//这里是a.length,不是a.lenght-1,因为后者会导致右数第2项没法参与排序。
if (a[inner] < a[min]) {
min = inner;
}
//将最小的项移动到左侧
tmp = a[out];
a[out] = a[min]
a[min] = tmp;
}
}
console.log(a);
})();
a = [66, 53, 11, 5, 4, 3, 2, 1];
/*插入排序*/
(function charupaixu() {
for (var out = 1; out < a.length; out++) {
var tmp = a[out];
var inner = out;
while (a[inner - 1] > tmp) {
a[inner] = a[inner - 1];
--inner;
}
a[inner] = tmp;
}
console.log(a);
})();
</script>
var a;
a = [66, 53, 11, 5, 4, 3, 2, 1];
/*冒泡排序*/
(function maopaopaixu() {
for (var i = 0; i < a.length - 1; i++) {//比较的次数是length-1
for (var j = 0; j < a.length - 1 - i; j++) {
if (a[j] > a[j + 1]) {
[a[j],a[j + 1]] = [a[j + 1],a[j]];
}
}
}
console.log(a);
})();
a = [66, 53, 11, 5, 4, 3, 2, 1];
/*选择排序*/
(function xuanzepaixu() {
var min/*最小项的索引*/, tmp;
for (var out = 0; out < a.length - 1; out++) {//比较的次数是length-1
min = out;
for (var inner = out + 1; inner < a.length; inner++) {//这里是a.length,不是a.lenght-1,因为后者会导致右数第2项没法参与排序。
if (a[inner] < a[min]) {
min = inner;
}
//将最小的项移动到左侧
tmp = a[out];
a[out] = a[min]
a[min] = tmp;
}
}
console.log(a);
})();
a = [66, 53, 11, 5, 4, 3, 2, 1];
/*插入排序*/
(function charupaixu() {
for (var out = 1; out < a.length; out++) {
var tmp = a[out];
var inner = out;
while (a[inner - 1] > tmp) {
a[inner] = a[inner - 1];
--inner;
}
a[inner] = tmp;
}
console.log(a);
})();
</script>
二分查找
function binarySearch(arr = [], tar, low = 0, high = arr.length - 1) { if (arr.indexOf(tar)==-1) return tar + " not in arr!"; let mid = Math.floor((low + high) / 2); if (arr[mid] == tar) { return "got " + tar + " at index=" + mid + "!"; } else if (tar > arr[mid]) { return binarySearch(arr, tar, mid + 1 < high ? mid + 1 : high, high); } else if (tar < arr[mid]) { return binarySearch(arr, tar, low, mid - 1); } return tar + " not in arr!"; } console.log(binarySearch([1, 2, 3, 4, 5], 4));
本博客所有随笔,若未明确标示为转载或未带有原文链接,皆为原创。
本博客所有随笔版权归博客园和kai.ma所有,欢迎转载,转载请保留:
本博客所有随笔版权归博客园和kai.ma所有,欢迎转载,转载请保留:
- 出处:http://kaima.cnblogs.com
- 作者:kai.ma