var exampleArr = [8, 94, 15, 88, 55, 76, 21, 39];
function sortArrByBubble(arr) {
for (i = 0; i < arr.length - 1; i++) {
for (j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
var temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
return arr;
}
sortArrByBubble(exampleArr);
console.log(exampleArr);
複製代碼
二路歸併排序主旨是「分解」與「歸併」算法
分解: 數組
一、將一個數組分紅兩個數組,分別對兩個數組進行排序。bash
二、循環第一步,直到劃分出來的「小數組」只包含一個元素,只有一個元素的數組默認爲已經排好序。測試
歸併:ui
function mergeSort(arr) {
// 設置終止的條件,
if (arr.length < 2) {
return arr;
}
//設立中間值
var middle = parseInt(arr.length / 2);
//第1個和middle個之間爲左子列
var left = arr.slice(0, middle);
//第middle+1到最後爲右子列
var right = arr.slice(middle);
if (left == "undefined" && right == "undefined") {
return false;
}
return merge(mergeSort(left), mergeSort(right));
}
function merge(left, right) {
var result = [];
while (left.length && right.length) {
if (left[0] <= right[0]) {
//把left的左子樹推出一個,而後push進result數組裏
result.push(left.shift());
} else {
//把right的右子樹推出一個,而後push進result數組裏
result.push(right.shift());
}
}
//通過上面一次循環,只能左子列或右子列一個不爲空,或者都爲空
while (left.length) {
result.push(left.shift());
}
while (right.length) {
result.push(right.shift());
}
return result;
}
// 測試數據
var nums = [6, 1, 4, 8, 2, 7, 3, 5];
console.log(mergeSort(nums))
複製代碼
function Fibonacci(n) {
if (n <= 1) {
return 1
}
return Fibonacci(n - 1) + Fibonacci(n - 2);
}
console.log(Fibonacci(8))
// 輸出結果34
複製代碼
二分法查找,也稱折半查找,是一種在有序數組中查找特定元素的搜索算法。 查找過程能夠分爲如下步驟:spa
非遞歸算法code
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 23, 44, 86];
function binarySearch(arr, key) {
var low = 0,
high = arr.length - 1;
while (low <= high) {
var mid = parseInt((high + low) / 2);
if (key == arr[mid]) {
return mid;
} else if (key > arr[mid]) {
low = mid + 1;
} else if (key < arr[mid]) {
high = mid - 1;
} else {
return -1;
}
}
};
var result = binarySearch(arr, 10);
console.log(result); // 9 返回目標元素的索引值
複製代碼
遞歸算法cdn
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 23, 44, 86];
function binarySearch(arr, low, high, key) {
if (low > high) {
return -1;
}
var mid = parseInt((high + low) / 2);
if (arr[mid] == key) {
return mid;
} else if (arr[mid] > key) {
high = mid - 1;
return binarySearch(arr, low, high, key);
} else if (arr[mid] < key) {
low = mid + 1;
return binarySearch(arr, low, high, key);
}
};
var result = binarySearch(arr, 0, 13, 10);
console.log(result); // 9 返回目標元素的索引值
複製代碼