mg4377娱乐娱城官网_mg4377娱乐手机版_www.mg4377.com

当前位置: mg4377娱乐娱城官网 > www.mg4377.com > 正文

JavaScript中常见排序算法详解,面试中常见算法难

时间:2019-10-21 07:02来源:www.mg4377.com
JavaScript 面试中常见算法难点详解 2017/02/20 · JavaScript· 1 评论 ·算法 初稿出处:王下邀月熊_Chevalier    JavaScript面试中常见算法难题详解 翻译自Interview Algorithm Questions in Javascript(){…}附

JavaScript 面试中常见算法难点详解

2017/02/20 · JavaScript · 1 评论 · 算法

初稿出处: 王下邀月熊_Chevalier   

JavaScript 面试中常见算法难题详解 翻译自 Interview Algorithm Questions in Javascript() {…} 附属于小编的 Web 前端入门与工程实践。下文提到的累累主题材料从算法角度并不必定要么困难,可是用 JavaScript 内置的 API 来成功也许须要大器晚成番勘验的。

图片 1

JavaScript Specification

正文提到的好多主题素材从算法角度并不应当要么困难,然则用 JavaScript 内置的 API 来成功也许要求龙腾虎跃番勘探的。
1.解说下 JavaScript 中的变量升高
所谓升高,看名就能够猜到其意义就是 JavaScript 会将兼具的宣示升高到当前功用域的最上部。那也就代表大家得以在某些变量注明前就选拔该变量,可是虽然JavaScript 会将宣示进步到顶上部分,可是并不会奉行真的先导化进度。
2.阐述下 use strict; 的作用

有句话怎么说来着:

解说下 JavaScript 中的变量提高

所谓升高,看名就会知道意思就是 JavaScript 会将具备的注解进步到目前功用域的最上端。那也就表示大家得以在有些变量申明前就应用该变量,可是固然如此 JavaScript 会将宣示升高到最上端,不过并不会实践真的开头化进度。

....

雷正兴推倒西塔,Java implements JavaScript.

阐述下 use strict; 的作用

use strict; 从名称想到所包括的意义也正是 JavaScript 会在所谓严俊格局下实行,其八个生死攸关的优势在于能够强制开垦者幸免使用未申明的变量。对于老版本的浏览器如故试行引擎则会自行忽视该指令。

JavaScript

// Example of strict mode "use strict"; catchThemAll(); function catchThemAll() { x = 3.14; // Error will be thrown return x * x; }

1
2
3
4
5
6
7
8
// Example of strict mode
"use strict";
 
catchThemAll();
function catchThemAll() {
  x = 3.14; // Error will be thrown
  return x * x;
}

那时,想凭仗抱Java大腿火后生可畏把而不惜把团结名字给改了的JavaScript(原名LiveScript),如明儿深夜就光辉灿烂。node JS的面世更是让JavaScript可早前后端通吃。固然Java依旧制霸集团级软件开垦领域(C/C 的大神们并不是打笔者。。。),但在Web的下方,JavaScript可谓风头无两,坐上了头把交椅。

解释下怎么样是 Event Bubbling 以致怎么着防止

伊夫nt Bubbling 即指有个别事件不止会触发当前成分,还恐怕会以嵌套顺序传递到父成分中。直观来说正是对此某些子元素的点击事件同样会被父元素的点击事件管理器捕获。幸免伊芙nt Bubbling 的艺术能够利用event.stopPropagation() 可能 IE 9 以下使用event.cancelBubble

只是,在守旧的管理器算法和数据结构领域,大非常多标准教材和图书的暗中同意语言都是Java或然C/C 。这给方今想恶补算法和数据结构知识的自身变成了料定麻烦,因为自身想搜寻一本以JavaScript为暗中认可语言的算法书籍。当自己询问到O’REILLY家的动物丛书种类里有一本叫做《数据结构与算法JavaScript描述》时,便高兴的花了两日时间把那本书从头至尾读了三回。它是一本很好的指向性前面多个开采者们的入门算法书籍,可是,它有一个十分大的劣势,便是内部有过多显著的小错误,明显到就连自家这种半道出家的技师都能生龙活虎眼看出来。还大概有四个主题材料是,比相当多关键的算法和数据结构知识并不以往在这里本书里被提到。这一个难题对于作为一个最后时期恐怖症病人的自己来讲大致无法忍。于是乎,一言不合小编就决定自个儿找资料计算算法。那么,笔者就从算法领域里最基础的知识点——排序算法计算起好了。

== 与 === 的区分是怎样

=== 也正是所谓的从严相比,关键的区分在于=== 会同期比较类型与值,并不是仅比较值。

JavaScript

// Example of comparators 0 == false; // true 0 === false; // false 2 == '2'; // true 2 === '2'; // false

1
2
3
4
5
6
// Example of comparators
0 == false; // true
0 === false; // false
 
2 == '2'; // true
2 === '2'; // false

本人深信以下的代码里断定会有有些bug或错误或语法不标准等难题是自家自身没辙察觉的,所以敬请各位大神能够提议错误,因为唯有在相连改错的征程上自个儿工夫赢得长期的向上。

解释下 null 与 undefined 的区别

JavaScript 中,null 是三个得以被分配的值,设置为 null 的变量意味着其无值。而 undefined 则意味着着有个别变量纵然声称了而是未有举办过任何赋值。

十大优秀算法

解释下 Prototypal Inheritance 与 Classical Inheritance 的区别

在类继承中,类是不可变的,不一样的语言中对于多一而再的支撑也分化等,某个语言中还援助接口、final、abstract 的定义。而原型承接则越来越灵活,原型本身是足以可变的,並且对象也许接二连三自八个原型。

一张图回顾:

数组

图片 2

寻找整型数组中乘积最大的四个数

给定一个含有整数的九冬数组,须要搜索乘积最大的四个数。

JavaScript

var unsorted_array = [-10, 7, 29, 30, 5, -10, -70]; computeProduct(unsorted_array); // 21000 function sortIntegers(a, b) { return a - b; } // greatest product is either (min1 * min2 * max1 || max1 * max2 * max3) function computeProduct(unsorted) { var sorted_array = unsorted.sort(sortIntegers), product1 = 1, product2 = 1, array_n_element = sorted_array.length - 1; // Get the product of three largest integers in sorted array for (var x = array_n_element; x > array_n_element - 3; x--) { product1 = product1 * sorted_array[x]; } product2 = sorted_array[0] * sorted_array[1] * sorted_array[array_n_element]; if (product1 > product2) return product1; return product2 };

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
var unsorted_array = [-10, 7, 29, 30, 5, -10, -70];
 
computeProduct(unsorted_array); // 21000
 
function sortIntegers(a, b) {
  return a - b;
}
 
// greatest product is either (min1 * min2 * max1 || max1 * max2 * max3)
function computeProduct(unsorted) {
  var sorted_array = unsorted.sort(sortIntegers),
    product1 = 1,
    product2 = 1,
    array_n_element = sorted_array.length - 1;
 
  // Get the product of three largest integers in sorted array
  for (var x = array_n_element; x > array_n_element - 3; x--) {
      product1 = product1 * sorted_array[x];
  }
  product2 = sorted_array[0] * sorted_array[1] * sorted_array[array_n_element];
 
  if (product1 > product2) return product1;
 
  return product2
};

名词解释:

查找接二连三数组中的缺点和失误数

给定某冬季数组,其含有了 n 个三番五次数字中的 n – 1 个,已知上下面界,要求以O(n)的复杂度寻觅缺点和失误的数字。

JavaScript

// The output of the function should be 8 var array_of_JavaScript中常见排序算法详解,面试中常见算法难点详解。integers = [2, 5, 1, 4, 9, 6, 3, 7]; var upper_bound = 9; var lower_bound = 1; findMissingNumber(array_of_integers, upper_bound, lower_bound); //8 function findMissingNumber(array_of_integers, upper_bound, lower_bound) { // Iterate through array to find the sum of the numbers var sum_of_integers = 0; for (var i = 0; i < array_of_integers.length; i ) { sum_of_integers = array_of_integers[i]; } // 以高斯求和公式总结理论上的数组和 // Formula: [(N * (N 1)) / 2] - [(M * (M - 1)) / 2]; // N is the upper bound and M is the lower bound upper_limit_sum = (upper_bound * (upper_bound 1)) / 2; lower_limit_sum = (lower_bound * (lower_bound - 1)) / 2; theoretical_sum = upper_limit_sum - lower_limit_sum; // return (theoretical_sum - sum_of_integers) }

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
// The output of the function should be 8
var array_of_integers = [2, 5, 1, 4, 9, 6, 3, 7];
var upper_bound = 9;
var lower_bound = 1;
 
findMissingNumber(array_of_integers, upper_bound, lower_bound); //8
 
function findMissingNumber(array_of_integers, upper_bound, lower_bound) {
 
  // Iterate through array to find the sum of the numbers
  var sum_of_integers = 0;
  for (var i = 0; i < array_of_integers.length; i ) {
    sum_of_integers = array_of_integers[i];
  }
 
  // 以高斯求和公式计算理论上的数组和
  // Formula: [(N * (N 1)) / 2] - [(M * (M - 1)) / 2];
  // N is the upper bound and M is the lower bound
 
  upper_limit_sum = (upper_bound * (upper_bound 1)) / 2;
  lower_limit_sum = (lower_bound * (lower_bound - 1)) / 2;
 
  theoretical_sum = upper_limit_sum - lower_limit_sum;
 
  //
  return (theoretical_sum - sum_of_integers)
}

n:数据规模

数组去重

给定某冬日数组,必要删除数组中的重复数字何况再次回到新的无重复数组。

JavaScript

// ES6 Implementation var array = [1, 2, 3, 5, 1, 5, 9, 1, 2, 8]; Array.from(new Set(array)); // [1, 2, 3, 5, 9, 8] // ES5 Implementation var array = [1, 2, 3, 5, 1, 5, 9, 1, 2, 8]; uniqueArray(array); // [1, 2, 3, 5, 9, 8] function uniqueArray(array) { var hashmap = {}; var unique = []; for(var i = 0; i < array.length; i ) { // If key returns null (unique), it is evaluated as false. if(!hashmap.hasOwnProperty([array[i]])) { hashmap[array[i]] = 1; unique.push(array[i]); } } return unique; }

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// ES6 Implementation
var array = [1, 2, 3, 5, 1, 5, 9, 1, 2, 8];
 
Array.from(new Set(array)); // [1, 2, 3, 5, 9, 8]
 
 
// ES5 Implementation
var array = [1, 2, 3, 5, 1, 5, 9, 1, 2, 8];
 
uniqueArray(array); // [1, 2, 3, 5, 9, 8]
 
function uniqueArray(array) {
  var hashmap = {};
  var unique = [];
  for(var i = 0; i < array.length; i ) {
    // If key returns null (unique), it is evaluated as false.
    if(!hashmap.hasOwnProperty([array[i]])) {
      hashmap[array[i]] = 1;
      unique.push(array[i]);
    }
  }
  return unique;
}

k:“桶”的个数

数组瓜月素最大差值总计

给定某冬季数组,求取任性两个要素之间的最大差值,注意,这里须要差值总括中极小的元素下标必需低于相当大因素的下标。比方[7, 8, 4, 9, 9, 15, 3, 1, 10]这几个数组的计算值是 11( 15 – 4 ) 并非 14(15 – 1),因为 15 的下标小于 1。

JavaScript

var array = [7, 8, 4, 9, 9, 15, 3, 1, 10]; // [7, 8, 4, 9, 9, 15, 3, 1, 10] would return `11` based on the difference between `4` and `15` // Notice: It is not `14` from the difference between `15` and `1` because 15 comes before 1. findLargestDifference(array); function findLargestDifference(array) { // 如若数组唯有一个要素,则直接回到 -1 if (array.length <= 1) return -1; // current_min 指向当前的小不点儿值 var current_min = array[0]; var current_max_difference = 0; // 遍历整个数组以求取当前最大差值,借使发掘某些最大差值,则将新的值覆盖 current_max_difference // 同时也会追踪当前数组中的最小值,进而保证 `largest value in future` - `smallest value before it` for (var i = 1; i < array.length; i ) { if (array[i] > current_min && (array[i] - current_min > current_max_difference)) { current_max_difference = array[i] - current_min; } else if (array[i] <= current_min) { current_min = array[i]; } } // If negative or 0, there is no largest difference if (current_max_difference <= 0) return -1; return current_max_difference; }

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
var array = [7, 8, 4, 9, 9, 15, 3, 1, 10];
// [7, 8, 4, 9, 9, 15, 3, 1, 10] would return `11` based on the difference between `4` and `15`
// Notice: It is not `14` from the difference between `15` and `1` because 15 comes before 1.
 
findLargestDifference(array);
 
function findLargestDifference(array) {
 
  // 如果数组仅有一个元素,则直接返回 -1
 
  if (array.length <= 1) return -1;
 
  // current_min 指向当前的最小值
 
  var current_min = array[0];
  var current_max_difference = 0;
  
  // 遍历整个数组以求取当前最大差值,如果发现某个最大差值,则将新的值覆盖 current_max_difference
  // 同时也会追踪当前数组中的最小值,从而保证 `largest value in future` - `smallest value before it`
 
  for (var i = 1; i < array.length; i ) {
    if (array[i] > current_min && (array[i] - current_min > current_max_difference)) {
      current_max_difference = array[i] - current_min;
    } else if (array[i] <= current_min) {
      current_min = array[i];
    }
  }
 
  // If negative or 0, there is no largest difference
  if (current_max_difference <= 0) return -1;
 
  return current_max_difference;
}

In-place:占用常数内部存款和储蓄器,不占用额外内部存款和储蓄器

数组瓜月素乘积

给定某冬辰数组,供给重回新数组 output ,此中 output[i] 为原数组中除去下标为 i 的因素之外的要素乘积,供给以 O(n) 复杂度实现:

JavaScript

var firstArray = [2, 2, 4, 1]; var secondArray = [0, 0, 0, 2]; var thirdArray = [-2, -2, -3, 2]; productExceptSelf(firstArray); // [8, 8, 4, 16] productExceptSelf(secondArray); // [0, 0, 0, 0] productExceptSelf(thirdArray); // [12, 12, 8, -12] function productExceptSelf(numArray) { var product = 1; var size = numArray.length; var output = []; // From first array: [1, 2, 4, 16] // The last number in this case is already in the right spot (allows for us) // to just multiply by 1 in the next step. // This step essentially gets the product to the left of the index at index 1 for (var x = 0; x < size; x ) { output.push(product); product = product * numArray[x]; } // From the back, we multiply the current output element (which represents the product // on the left of the index, and multiplies it by the product on the right of the element) var product = 1; for (var i = size - 1; i > -1; i--) { output[i] = output[i] * product; product = product * numArray[i]; } return output; }

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
var firstArray = [2, 2, 4, 1];
var secondArray = [0, 0, 0, 2];
var thirdArray = [-2, -2, -3, 2];
 
productExceptSelf(firstArray); // [8, 8, 4, 16]
productExceptSelf(secondArray); // [0, 0, 0, 0]
productExceptSelf(thirdArray); // [12, 12, 8, -12]
 
function productExceptSelf(numArray) {
  var product = 1;
  var size = numArray.length;
  var output = [];
 
  // From first array: [1, 2, 4, 16]
  // The last number in this case is already in the right spot (allows for us)
  // to just multiply by 1 in the next step.
  // This step essentially gets the product to the left of the index at index 1
  for (var x = 0; x < size; x ) {
      output.push(product);
      product = product * numArray[x];
  }
 
  // From the back, we multiply the current output element (which represents the product
  // on the left of the index, and multiplies it by the product on the right of the element)
  var product = 1;
  for (var i = size - 1; i > -1; i--) {
      output[i] = output[i] * product;
      product = product * numArray[i];
  }
 
  return output;
}

Out-place:占用额外内部存款和储蓄器

数组交集

给定三个数组,供给求出三个数组的混杂,注意,交集中的因素应该是头一无二的。

JavaScript

var firstArray = [2, 2, 4, 1]; var secondArray = [1, 2, 0, 2]; intersection(firstArray, secondArray); // [2, 1] function intersection(firstArray, secondArray) { // The logic here is to create a hashmap with the elements of the firstArray as the keys. // After that, you can use the hashmap's O(1) look up time to check if the element exists in the hash // If it does exist, add that element to the new array. var hashmap = {}; var intersectionArray = []; firstArray.forEach(function(element) { hashmap[element] = 1; }); // Since we only want to push unique elements in our case... we can implement a counter to keep track of what we already added secondArray.forEach(function(element) { if (hashmap[element] === 1) { intersectionArray.push(element); hashmap[element] ; } }); return intersectionArray; // Time complexity O(n), Space complexity O(n) }

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
var firstArray = [2, 2, 4, 1];
var secondArray = [1, 2, 0, 2];
 
intersection(firstArray, secondArray); // [2, 1]
 
function intersection(firstArray, secondArray) {
  // The logic here is to create a hashmap with the elements of the firstArray as the keys.
  // After that, you can use the hashmap's O(1) look up time to check if the element exists in the hash
  // If it does exist, add that element to the new array.
 
  var hashmap = {};
  var intersectionArray = [];
 
  firstArray.forEach(function(element) {
    hashmap[element] = 1;
  });
 
  // Since we only want to push unique elements in our case... we can implement a counter to keep track of what we already added
  secondArray.forEach(function(element) {
    if (hashmap[element] === 1) {
      intersectionArray.push(element);
      hashmap[element] ;
    }
  });
 
  return intersectionArray;
 
  // Time complexity O(n), Space complexity O(n)
}

和煦:排序后2个卓殊键值的各样和排序此前它们的各类同样

字符串

冒泡排序

颠倒字符串

加以某些字符串,必要将在那之中单词倒转之后然后输出,举例”Welcome to this Javascript Guide!” 应该出口为 “emocleW ot siht tpircsavaJ !ediuG”。

JavaScript

var string = "Welcome to this Javascript Guide!"; // Output becomes !ediuG tpircsavaJ siht ot emocleW var reverseEntireSentence = reverseBySeparator(string, ""); // Output becomes emocleW ot siht tpircsavaJ !ediuG var reverseEachWord = reverseBySeparator(reverseEntireSentence, " "); function reverseBySeparator(string, separator) { return string.split(separator).reverse().join(separator); }

1
2
3
4
5
6
7
8
9
10
11
var string = "Welcome to this Javascript Guide!";
 
// Output becomes !ediuG tpircsavaJ siht ot emocleW
var reverseEntireSentence = reverseBySeparator(string, "");
 
// Output becomes emocleW ot siht tpircsavaJ !ediuG
var reverseEachWord = reverseBySeparator(reverseEntireSentence, " ");
 
function reverseBySeparator(string, separator) {
  return string.split(separator).reverse().join(separator);
}

用作最简便的排序算法之意气风发,冒泡排序给我的以为到就好像Abandon在单词书里出现的以为同样,每一次都在首先页第一人,所以最纯熟。。。冒泡排序还大概有黄金年代种优化算法,便是立多少个flag,当在如日中天趟类别遍历中元素未有发出沟通,则印证该系列已经平稳。但这种立异对于晋级品质来讲并从未什么样太大职能。。。

乱序同字母字符串

给定四个字符串,剖断是或不是颠倒字母而成的字符串,比如MaryArmy不畏同字母而相继颠倒:

JavaScript

var firstWord = "Mary"; var secondWord = "Army"; isAnagram(firstWord, secondWord); // true function isAnagram(first, second) { // For case insensitivity, change both words to lowercase. var a = first.toLowerCase(); var b = second.toLowerCase(); // Sort the strings, and join the resulting array to a string. Compare the results a = a.split("").sort().join(""); b = b.split("").sort().join(""); return a === b; }

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var firstWord = "Mary";
var secondWord = "Army";
 
isAnagram(firstWord, secondWord); // true
 
function isAnagram(first, second) {
  // For case insensitivity, change both words to lowercase.
  var a = first.toLowerCase();
  var b = second.toLowerCase();
 
  // Sort the strings, and join the resulting array to a string. Compare the results
  a = a.split("").sort().join("");
  b = b.split("").sort().join("");
 
  return a === b;
}

怎么样时候最快

会问字符串

看清有些字符串是还是不是为回文字符串,比如racecarrace car都以回文字符串:

JavaScript

isPalindrome("racecar"); // true isPalindrome("race Car"); // true function isPalindrome(word) { // Replace all non-letter chars with "" and change to lowercase var lettersOnly = word.toLowerCase().replace(/s/g, ""); // Compare the string with the reversed version of the string return lettersOnly === lettersOnly.split("").reverse().join(""); }

1
2
3
4
5
6
7
8
9
10
isPalindrome("racecar"); // true
isPalindrome("race Car"); // true
 
function isPalindrome(word) {
  // Replace all non-letter chars with "" and change to lowercase
  var lettersOnly = word.toLowerCase().replace(/s/g, "");
 
  // Compare the string with the reversed version of the string
  return lettersOnly === lettersOnly.split("").reverse().join("");
}

当输入的多寡现已经是正序时(都曾经是正序了,作者还要你冒泡排序有啥用啊。。。。)

栈与队列

哪些时候最慢

使用七个栈达成入队与出队

JavaScript

var inputStack = []; // First stack var outputStack = []; // Second stack // For enqueue, just push the item into the first stack function enqueue(stackInput, item) { return stackInput.push(item); } function dequeue(stackInput, stackOutput) { // Reverse the stack such that the first element of the output stack is the // last element of the input stack. After that, pop the top of the output to // get the first element that was ever pushed into the input stack if (stackOutput.length <= 0) { while(stackInput.length > 0) { var elementToOutput = stackInput.pop(); stackOutput.push(elementToOutput); } } return stackOutput.pop(); }

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
var inputStack = []; // First stack
var outputStack = []; // Second stack
 
// For enqueue, just push the item into the first stack
function enqueue(stackInput, item) {
  return stackInput.push(item);
}
 
function dequeue(stackInput, stackOutput) {
  // Reverse the stack such that the first element of the output stack is the
  // last element of the input stack. After that, pop the top of the output to
  // get the first element that was ever pushed into the input stack
  if (stackOutput.length <= 0) {
    while(stackInput.length > 0) {
      var elementToOutput = stackInput.pop();
      stackOutput.push(elementToOutput);
    }
  }
 
  return stackOutput.pop();
}

当输入的数目是反序时(写三个for循环反序输出数据不就行了,干嘛要用你冒泡排序呢,作者是闲的呢。。。)

推断大括号是不是关闭

开创二个函数来决断给定的表明式中的大括号是不是关闭:

JavaScript

var expression = "{{}}{}{}" var expressionFalse = "{}{{}"; isBalanced(expression); // true isBalanced(expressionFalse); // false isBalanced(""); // true function isBalanced(expression) { var checkString = expression; var stack = []; // If empty, parentheses are technically balanced if (checkString.length <= 0) return true; for (var i = 0; i < checkString.length; i ) { if(checkString[i] === '{') { stack.push(checkString[i]); } else if (checkString[i] === '}') { // Pop on an empty array is undefined if (stack.length > 0) { stack.pop(); } else { return false; } } } // If the array is not empty, it is not balanced if (stack.pop()) return false; return true; }

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
var expression = "{{}}{}{}"
var expressionFalse = "{}{{}";
 
isBalanced(expression); // true
isBalanced(expressionFalse); // false
isBalanced(""); // true
 
function isBalanced(expression) {
  var checkString = expression;
  var stack = [];
 
  // If empty, parentheses are technically balanced
  if (checkString.length <= 0) return true;
 
  for (var i = 0; i < checkString.length; i ) {
    if(checkString[i] === '{') {
      stack.push(checkString[i]);
    } else if (checkString[i] === '}') {
      // Pop on an empty array is undefined
      if (stack.length > 0) {
        stack.pop();
      } else {
        return false;
      }
    }
  }
 
  // If the array is not empty, it is not balanced
  if (stack.pop()) return false;
  return true;
}

冒泡排序动图演示

递归

图片 3

二进制转变

经过某些递归函数将输入的数字转变为二进制字符串:

JavaScript

decimalToBinary(3); // 11 decimalToBinary(8); // 1000 decimalToBinary(1000); // 1111101000 function decimalToBinary(digit) { if(digit >= 1) { // If digit is not divisible by 2 then recursively return proceeding // binary of the digit minus 1, 1 is added for the leftover 1 digit if (digit % 2) { return decimalToBinary((digit - 1) / 2) 1; } else { // Recursively return proceeding binary digits return decimalToBinary(digit / 2) 0; } } else { // Exit condition return ''; } }

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
decimalToBinary(3); // 11
decimalToBinary(8); // 1000
decimalToBinary(1000); // 1111101000
 
function decimalToBinary(digit) {
  if(digit >= 1) {
    // If digit is not divisible by 2 then recursively return proceeding
    // binary of the digit minus 1, 1 is added for the leftover 1 digit
    if (digit % 2) {
      return decimalToBinary((digit - 1) / 2) 1;
    } else {
      // Recursively return proceeding binary digits
      return decimalToBinary(digit / 2) 0;
    }
  } else {
    // Exit condition
    return '';
  }
}

JavaScript代码达成

二分查找

JavaScript

function recursiveBinarySearch(array, value, leftPosition, rightPosition) { // Value DNE if (leftPosition > rightPosition) return -1; var middlePivot = Math.floor((leftPosition rightPosition) / 2); if (array[middlePivot] === value) { return middlePivot; } else if (array[middlePivot] > value) { return recursiveBinarySearch(array, value, leftPosition, middlePivot - 1); } else { return recursiveBinarySearch(array, value, middlePivot 1, rightPosition); } }

1
2
3
4
5
6
7
8
9
10
11
12
13
function recursiveBinarySearch(array, value, leftPosition, rightPosition) {
  // Value DNE
  if (leftPosition > rightPosition) return -1;
 
  var middlePivot = Math.floor((leftPosition rightPosition) / 2);
  if (array[middlePivot] === value) {
    return middlePivot;
  } else if (array[middlePivot] > value) {
    return recursiveBinarySearch(array, value, leftPosition, middlePivot - 1);
  } else {
    return recursiveBinarySearch(array, value, middlePivot 1, rightPosition);
  }
}
function bubbleSort(arr) {     var len = arr.length;     for (var i = 0; i < len; i  ) {         for (var j = 0; j < len - 1 - i; j  ) {             if (arr[j] > arr[j 1]) {        //相邻元素两两对比                 var temp = arr[j 1];        //元素交换                 arr[j 1] = arr[j];                 arr[j] = temp;             }         }     }     return arr; } 

数字

选料排序

剖断是还是不是为 2 的指数值

JavaScript

isPowerOfTwo(4); // true isPowerOfTwo(64); // true isPowerOfTwo(1); // true isPowerOfTwo(0); // false isPowerOfTwo(-1); // false // For the non-zero case: function isPowerOfTwo(number) { // `&` uses the bitwise n. // In the case of number = 4; the expression would be identical to: // `return (4 & 3 === 0)` // In bitwise, 4 is 100, and 3 is 011. Using &, if two values at the same // spot is 1, then result is 1, else 0. In this case, it would return 000, // and thus, 4 satisfies are expression. // In turn, if the expression is `return (5 & 4 === 0)`, it would be false // since it returns 101 & 100 = 100 (NOT === 0) return number & (number - 1) === 0; } // For zero-case: function isPowerOfTwoZeroCase(number) { return (number !== 0) && ((number & (number - 1)) === 0); }

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
isPowerOfTwo(4); // true
isPowerOfTwo(64); // true
isPowerOfTwo(1); // true
isPowerOfTwo(0); // false
isPowerOfTwo(-1); // false
 
// For the non-zero case:
function isPowerOfTwo(number) {
  // `&` uses the bitwise n.
  // In the case of number = 4; the expression would be identical to:
  // `return (4 & 3 === 0)`
  // In bitwise, 4 is 100, and 3 is 011. Using &, if two values at the same
  // spot is 1, then result is 1, else 0. In this case, it would return 000,
  // and thus, 4 satisfies are expression.
  // In turn, if the expression is `return (5 & 4 === 0)`, it would be false
  // since it returns 101 & 100 = 100 (NOT === 0)
 
  return number & (number - 1) === 0;
}
 
// For zero-case:
function isPowerOfTwoZeroCase(number) {
  return (number !== 0) && ((number & (number - 1)) === 0);
}

 

3 赞 12 收藏 1 评论

图片 4

表现最平静的排序算法之龙腾虎跃,因为不论什么数据进去都以O(n²)的时间复杂度。。。所以用到它的时候,数据规模越小越好。唯生意盎然的裨益只怕就是不占用额外的内部存款和储蓄器空间了吧。

挑选排序动图演示

图片 5

JavaScript代码实现

function selectionSort(arr) {      var len = arr.length;      var minIndex, temp;      for (var i = 0; i < len - 1; i  ) {          minIndex = i;          for (var j = i   1; j < len; j  ) {              if (arr[j] < arr[minIndex]) {     //寻找最小的数                  minIndex = j;                 //将最小数的索引保存              }          }          temp = arr[i];          arr[i] = arr[minIndex];          arr[minIndex] = temp;      }      return arr;  } 

插入排序

插入排序的代码实现即便并未有冒泡排序和甄选排序那么粗略凶暴,但它的法规应该是最轻易驾驭的了,因为只要打过扑克牌的人都应有力所能致秒懂。当然,假诺你说你打扑克牌摸牌的时候从不按牌的尺寸整理牌,这预计那辈子你对插入排序的算法都不会生出其余兴趣了。。。

插入排序和冒泡排序同样,也可能有风度翩翩种优化算法,叫做拆半插入。对于这种算法,得了懒癌的自身就沿用教科书上的一句非凡的话吧:感兴趣的同窗能够在课后机关钻研。。。

编辑:www.mg4377.com 本文来源:JavaScript中常见排序算法详解,面试中常见算法难

关键词: JavaScript 开发 JS 前端 面试