Home >Web Front-end >JS Tutorial >Summary of some common algorithms in JavaScript_javascript skills

Summary of some common algorithms in JavaScript_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:22:551034browse

Here is a brief list of some common algorithms in JavaScript. Friends in need can refer to them. Of course, these algorithms are not only applicable to JavaScript, but also to other languages.

1. Linear search:

Relatively simple, entry-level algorithm

//A为数组,x为要搜索的值
function linearSearch(A, x) {
for (var index = 0; index < A.length; index++) {
if (A[index] == x) {
return index;
}
}
return -1;
}

2. Binary search:

Also known as half search, it is suitable for sorted linear structures.

//A为已按"升序排列"的数组,x为要查询的元素
//返回目标元素的下标
function binarySearch(A, x) {
var low = 0, high = A.length - 1;
while (low <= high) {
var mid = Math.floor((low + high) / 2); //下取整 
if (x == A[mid]) {
return mid;
}
if (x < A[mid]) {
high = mid - 1;
}
else {
low = mid + 1;
}
}
return -1;
}

3. Bubble sort:

//冒泡排序
function bubbleSort(A) {
for (var i = 0; i < A.length; i++) {
var sorted = true;
//注意:内循环是倒着来的
for (var j = A.length - 1; j > i; j--) {
if (A[j] < A[j - 1]) {
swap(A, j, j - 1);
sorted = false;
}
}
if (sorted) {
return;
}
}
}

4. Insertion sort:

//插入排序
//假定当前元素之前的元素已经排好序,先把自己的位置空出来,
//然后前面比自己大的元素依次向后移,直到空出一个"坑",
//然后把目标元素插入"坑"中
function insertSort(A) {
for (var index= 1; index< A.length; index++) {
var x = A[index];
for (var j = index- 1; j >= 0 && A[j] > x; j--) {
A[j + 1] = A[j];
}
if (A[j + 1] != x) {
A[j + 1] = x;
println(A);
}
}
return A;
}

5. String reversal:

//字符串反转(比如:ABC -> CBA)
function inverse(s) {
var arr = s.split('');
var index= 0, j = arr.length - 1;
while (index< j) {
var t = arr[index];
arr[index] = arr[j];
arr[j] = t;
index++;
j--;
}
return arr.join('');
}

The above content briefly introduces a summary of common JavaScript algorithms. I hope this article can help you.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn