加载笔记内容...
加载笔记内容...
1function constantTime(arr) {
2 return arr[0];
3}
1function binarySearch(arr, target) {
2 let left = 0;
3 let right = arr.length - 1;
4
5 while (left <= right) {
6 const mid = Math.floor((left + right) / 2);
7
8 if (arr[mid] === target) {
9 return mid;
10 }
11
12 if (arr[mid] < target) {
13 left = mid + 1;
14 } else {
15 right = mid - 1;
16 }
17 }
18
19 return -1;
20}
1function linearSearch(arr, target) {
2 for (let i = 0; i < arr.length; i++) {
3 if (arr[i] === target) {
4 return i;
5 }
6 }
7
8 return -1;
9}
1function mergeSort(arr) {
2 if (arr.length <= 1) {
3 return arr;
4 }
5
6 const mid = Math.floor(arr.length / 2);
7 const left = mergeSort(arr.slice(0, mid));
8 const right = mergeSort(arr.slice(mid));
9
10 return merge(left, right);
11}
12
13function merge(left, right) {
14 const result = [];
15
16 while (left.length && right.length) {
17 if (left[0] < right[0]) {
18 result.push(left.shift());
19 } else {
20 result.push(right.shift());
21 }
22 }
23
24 return [...result, ...left, ...right];
25}
1function bubbleSort(arr) {
2 for (let i = 0; i < arr.length; i++) {
3 for (let j = 0; j < arr.length - i - 1; j++) {
4 if (arr[j] > arr[j + 1]) {
5 [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
6 }
7 }
8 }
9
10 return arr;
11}
这个复杂度可以视为等差数列的和,从 1 到 (n-1)。在渐进意义上,O(n*(n-1)/2) 仍然等于 O(n^2)
1function fibonacci(n) {
2 if (n <= 1) {
3 return n;
4 }
5
6 return fibonacci(n - 1) + fibonacci(n - 2);
7}