9 Sorting Algorithms Implemented in JavaScript

Written interviews often involve various algorithms. This article briefly introduces some commonly used algorithms and implements them in javascript .

1. Insertion Sort

1) Algorithm

Introduction The algorithm description of Insertion-Sort is a simple and intuitive sorting algorithm . It works by building an ordered sequence, and for unsorted data, scans backwards and forwards in the sorted sequence, finds the corresponding position and inserts it. In terms of implementation of insertion sort, in-place sorting is usually used (that is, sorting that only uses O(1) extra space), so in the process of scanning from back to front, it is necessary to repeatedly move the sorted elements backward step by step. , to provide insertion space for the newest element.

2) Algorithm description and implementation

Generally speaking , insertion sort is implemented on the array using in-place. The specific algorithm is described as follows:

starting from the first element, the element can be considered to have been sorted;

take out the next element, and scan from the back to the front in the sorted element sequence;

if the element (sorted) is larger than the new element, it will Move the element to the next position;

repeat step 3 until the position where the sorted element is less than or equal to the new element is found;

after inserting the new element at this position;

repeat steps 2~5.

JavaScript code implementation:

function insertionSort(array) {
if (Object. prototype .toString.call(array).slice(8, -1) === 'Array') {
for (var i = 1; i < array.length; i++) {
var key = array[i];
var j = i – 1;
while (j >= 0 && array[j] > key) {
array[j + 1] = array[j];
j–;
}
array[j + 1] = key;
}
return array;
} else {
return 'array is not an Array!';
}
}

3) Algorithm analysis

Best case: input array Sort in ascending order. T(n) = O(n)

worst case: the input array is in descending order. T(n) = O(n2)

Average situation: T(n) = O(n2)

Second, binary insertion sort

1) Algorithm

Introduction Binary-insert-sort sorting is a kind of direct insertion sorting algorithm. Minor changes to the sorting algorithm. The biggest difference between it and the direct insertion sorting algorithm is that the method of binary search is used to find the insertion position, which has a certain improvement in speed.

2) Algorithm description and implementation

Generally speaking , insertion sort is implemented on the array using in-place. The specific algorithm is described as follows:

starting from the first element, the element can be considered to have been sorted;

Take out the next element, find the position of the first number larger than it in the sorted element sequence by binary search;

insert the new element into this position;

repeat the above two steps.

JavaScript code implementation:

function binaryInsertionSort(array) {
if (Object.prototype.toString.call(array).slice(8, -1) === 'Array') {
for (var i = 1; i < array.length ; i++) {
var key = array[i], left = 0, right = i – 1;
while (left <= right) {
var middle = parseInt((left + right) / 2);
if (key < array[ middle]) {
right = middle – 1;
} else {
left = middle + 1;
}
}
for (var j = i – 1; j >= left; j–) {
array[j + 1] = array[j] ;
}
array[left] = key;
}
return array;
} else {
return 'array is not an Array!';
}
}

3) Algorithm analysis

Best case: T(n) = O(nlogn)

Worst case: T(n) = O(n2)

Average case: T(n) = O(n2)

3. Selection sort

1) Introduction to the

algorithm Selection-sort (Selection-sort) is a simple and intuitive sorting algorithm. How it works: first find the smallest (largest) element in the unsorted sequence, store it at the beginning of the sorted sequence, then continue to find the smallest (largest) element from the remaining unsorted elements, and put it in the sorted sequence end of . And so on until all elements are sorted.

2) Algorithm description and realization

of direct selection sorting of n records The ordered results can be obtained after n-1 times of direct selection sorting. The specific algorithm is described as follows:

Initial state: the disordered area is R[1..n], and the ordered area is empty;

when the i-th sorting (i=1,2,3...n-1) starts, the current ordered area is empty. and disordered regions are R[1..i-1] and R(i..n), respectively. This sorting selects the record R[k] with the smallest key from the current unordered area, and exchanges it with the first record R in the unordered area, so that R[1..i] and R[i+1. .n) become a new ordered area with an increase in the number of records by 1 and a new unordered area with a decrease in the number of records by 1;

n-1 times are over, and the array is ordered.

JavaScript code implementation:

function selectionSort(array) {
if (Object.prototype.toString.call(array).slice(8, -1) === 'Array') {
var len = array.length, temp;
for (var i = 0; i < len - 1; i++) {
var min = array[i];
for (var j = i + 1; j < len; j++) {
if (array[j] < min) {
temp = min;
min = array[j];
array[j] = temp;
}
}
array[i] = min;
}
return array;
} else {
return 'array is not an Array !';
}
}

3) Algorithm analysis

Best case: T(n) = O(n2)

Worst case: T(n) = O(n2)

Average case: T(n) = O(n2)

Fourth, risk Bubble Sort

1) Algorithm Introduction

Bubble sort is a simple sorting algorithm. It repeatedly walks through the sequence to be sorted, comparing two elements at a time, and swapping them if they are in the wrong order. The work of visiting the sequence is repeated until no more exchanges are needed, that is, the sequence has been sorted. The name of this algorithm comes from the fact that the smaller elements are slowly "floated" to the top of the sequence by swapping.

2) Algorithm description and implementation

The specific algorithm is described as follows:

Compare adjacent elements. If the first is larger than the second, swap the two;

do the same for each pair of adjacent elements, from the first pair at the beginning to the last pair at the end, so the element at the end should be the largest number;

repeat the above steps for all elements except the last one;

repeat steps 1~3 until the sorting is complete.

JavaScript code implementation:

function bubbleSort(array) {
if (Object.prototype.toString.call(array).slice(8, -1) === 'Array') {
var len = array.length, temp;
for (var i = 0; i < len – 1; i++) {
for (var j = len – 1; j >= i; j–) {
if (array[j] < array[j - 1]) {
temp = array[ j];
array[j] = array[j - 1];
array[j - 1] = temp;
}
}
}
return array;
} else {
return 'array is not an Array!';
}
}

3) Algorithm analysis

The most Best case: T(n) = O(n)

Worst case: T(n) = O(n2)

Average case: T(n) = O(n2)

5. Quick sort

1) Introduction to the

algorithm The basic idea of ​​quick sort: separate the records to be sorted into independent If the keywords of one part of the records are smaller than the keywords of the other part, the records of the two parts can be sorted separately to achieve the order of the whole sequence.

2) Algorithm description and

implementation Quicksort uses the divide and conquer method to divide a string (list) into two sub-strings (sub-lists). The specific algorithm is described as follows:

pick out an element from the sequence, called "pivot";

reorder the sequence, all elements smaller than the benchmark value are placed in front of the benchmark, and all elements larger than the benchmark value are placed at the bottom of the benchmark back (same numbers can go to either side). After the partition exits, the benchmark is in the middle of the sequence. This is called a partition operation;

recursively sorts subarrays of elements smaller than the base value and subarrays of elements larger than the base value.

JavaScript code implementation:

//Method one
function quickSort(array, left, right) {
if (Object.prototype.toString.call(array).slice(8, -1) === 'Array' && typeof left === 'number' && typeof right === 'number') {
if (left < right) {
var x = array[right], i = left – 1, temp;
for (var j = left; j <= right; j++) {
if (array[j] <= x) {
i++;
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
quickSort(array, left, i – 1);
quickSort(array, i + 1, right);
};
} else {
return ‘array is not an Array or left or right is not a number!’;
}
}
var aaa = [3, 5, 2, 9, 1];
quickSort(aaa, 0, aaa.length – 1);
console.log(aaa);

//方法二
var quickSort = function(arr) {
if (arr.length <= 1) { return arr; }
var pivotIndex = Math.floor(arr.length / 2);
var pivot = arr.splice(pivotIndex, 1)[0];
var left = [];
var right = [];
for (var i = 0; i < arr.length; i++){
if (arr[i] < pivot) {
left.push(arr[i]);
} else {
right.push(arr[i]);
}
}
return quickSort(left).concat([pivot], quickSort(right));
};

3) Algorithm analysis

Best case: T(n) = O(nlogn)

Worst case: T(n) = O(n2)

Average case: T(n) = O (

nlogn )

a sorting algorithm. Stacking is a structure that approximates a complete binary tree, and at the same time satisfies the property of stacking: that is, the key value or index of a child node is always less than (or greater than) its parent node. 2) Description and implementation of the algorithm The last element R[n] is exchanged, and a new disordered area (R1, R2,...Rn-1) and a new ordered area (Rn) are obtained at this time, and R[1,2...n- 1]<=R[n];











Since the new heap top R[1] after the swap may violate the properties of the heap, it is necessary to adjust the current disordered area (R1, R2, ... Rn-1) to a new heap, and then re-align R[1] with the disordered The last element of the region is exchanged to obtain a new disordered region (R1, R2....Rn-2) and a new ordered region (Rn-1, Rn). This process is repeated until the number of elements in the ordered area is n-1, and the entire sorting process is completed.

JavaScript code implementation:

/*Method description: heap sort
@param array array to be sorted*/
function heapSort(array) {
if (Object.prototype.toString.call(array).slice(8, -1) === 'Array ') {
//build heap
var heapSize = array.length, temp;
for (var i = Math.floor(heapSize / 2); i >= 0; i–) {
heapify(array, i, heapSize);
}

/ /
heapsort for (var j = heapSize – 1; j >= 1; j–) {
temp = array[0];
array[0] = array[j];
array[j] = temp;
heapify(array, 0 , --heapSize);
}
} else {
return ‘array is not an Array!’;
}
}
/*方法说明:维护堆的性质
@param arr 数组
@param x 数组下标
@param len 堆大小*/
function heapify(arr, x, len) {
if (Object.prototype.toString.call(arr).slice(8, -1) === ‘Array’ && typeof x === ‘number’) {
var l = 2 * x, r = 2 * x + 1, largest = x, temp;
if (l < len && arr[l] > arr[largest]) {
largest = l;
}
if (r < len && arr[r] > arr[largest]) {
largest = r;
}
if (largest != x) {
temp = arr[x];
arr[x] = arr[largest];
arr[largest] = temp;
heapify(arr, largest, len);
}
} else {
return 'arr is not an Array or x is not a number!';
}
}

3) Algorithm analysis

Best case: T(n) = O(nlogn)

Worst case: T(n) = O(nlogn)

Average case : T(n) = O(nlogn)

7. Merge sort

1) Introduction to the algorithm

Merge sort is an effective sorting algorithm based on the merge operation. This algorithm is a very typical application of Divide and Conquer. Merge sort is a stable sorting method. Merge the ordered subsequences to obtain a completely ordered sequence; that is, first make each subsequence ordered, and then make the subsequence segments ordered. If two sorted lists are merged into one sorted list, it is called 2-way merge.

2) Algorithm description and implementation

The specific algorithm is described as follows:

divide the input sequence of length n into two subsequences of length n/2;

use merge sort on these two subsequences respectively; merge

the two sorted subsequences into a A final sorted sequence.

JavaScript code implementation:

function mergeSort(array, p, r) {
if (p < r) {
var q = Math.floor((p + r) / 2);
mergeSort(array, p, q);
mergeSort(array, q + 1, r);
merge(array, p, q, r);
}
}
function merge(array, p, q, r) {
var n1 = q – p + 1, n2 = r – q, left = [], right = [], m = n = 0;
for (var i = 0; i < n1; i++) {
left[i] = array[p + i];
}
for (var j = 0; j < n2; j++) {
right[j] = array[q + 1 + j];
}
left[n1] = right[n2] = Number.MAX_VALUE;
for (var k = p; k <= r; k++) {
if (left[m] <= right[n]) {
array[k] = left [m];
m++;
} else {
array[k] = right[n];
n++;
}
}
}

3) Algorithm analysis

Best case: T(n) = O(n)

Worst case: T(n) = O(nlogn)

average case: T(n) = O(nlogn)

Eight, bucket sorting

1) Introduction to the algorithm

The working principle of bucket sort (Bucket sort): Assuming that the input data is uniformly distributed, the data is divided into a limited number of buckets, and each bucket is sorted separately (it is possible to use another sorting algorithm or continue to use it recursively. bucket sort).

2) Algorithm description and implementation

The specific algorithm is described as follows:

set a quantitative array as an empty bucket;

traverse the input data, and put the data into the corresponding buckets one by one;

sort each bucket that is not empty;

never The sorted data is spliced ​​together in the empty bucket.

JavaScript code implementation:

/*Method description: bucket sort
@param array array
@param num number of buckets */
function bucketSort(array, num) {
if (array.length <= 1) {
return array;
}
var len = array. length, buckets = [], result = [], min = max = array[0], regex = '/^[1-9]+[0-9]*$/', space, n = 0;
num = num || ((num > 1 && regex.test(num)) ? num : 10);
for (var i = 1; i < len; i++) {
min = min <= array[i] ? min : array[ i];
max = max >= array[i] ? max : array[i];
}
space = (max – min + 1) / num;
for (var j = 0; j < len; j++) {
var index = Math.floor((array[j] – min) / space);
if (buckets[index]) { // 非空桶,插入排序
var k = buckets[index].length – 1;
while (k >= 0 && buckets[index][k] > array[j]) {
buckets[index][k + 1] = buckets[index][k];
k–;
}
buckets[index][k + 1] = array[j];
} else { //空桶,初始化
buckets[index] = [];
buckets[index].push(array[j]);
}
}
while (n < num) {
result = result.concat(buckets[n]);
n++;
}
return result;
}

3)算法分析

The best case of bucket sorting uses linear time O(n). The time complexity of bucket sorting depends on the time complexity of sorting the data between each bucket, because the time complexity of other parts is O(n). Obviously, the smaller the buckets are divided, the less data there is between the buckets, and the less time it takes to sort. But the corresponding space consumption will increase.

9. Counting sort

1) Introduction to the

algorithm Counting sort (Counting sort) is a stable sorting algorithm. Counting sort uses an additional array C, where the ith element is the number of elements in the array A to be sorted whose value is equal to i. Then according to the array C to arrange the elements in A to the correct position. It can only sort integers.

2) Algorithm description and implementation

The specific algorithm is described as follows:

find the largest and smallest elements in the array to be sorted;

count the number of occurrences of each element whose value is i in the array, and store it in the i-th item of array C

; Count accumulation (starting from the first element in C, each item is added to the previous item);

fill the target array in reverse: place each element i in the C(i)th item of the new array, and place each element, then subtract 1 from C(i).

JavaScript code implementation:

function countingSort(array) {
var len = array.length, B = [], C = [], min = max = array[0];
for (var i = 0; i < len; i++) {
min = min <= array[i] ? min : array[i];
max = max >= array[i] ? max : array[i];
C[array[i]] = C[array[i]] ? C[array[i]] + 1 : 1;
}
for (var j = min; j < max; j++) {
C[j + 1] = (C[j + 1] || 0) + (C[j] || 0);
}
for (var k = len – 1; k >=0; k–) {
B[C[array[k]] – 1] = array[k];
C[array[k]]–;
}
return B;
}

3) Algorithm analysis

When the input elements are n integers between 0 and k, its running time is O( n + k). Counting sort is not a comparison sort, and it sorts faster than any comparison sort algorithm. Since the length of the array C used for counting depends on the range of data in the array to be sorted (equal to the difference between the maximum value and the minimum value of the array to be sorted plus 1), this makes counting sorting for arrays with a large data range, requiring a large number of time and memory.

Original link: http://www.kubiji.cn/juhe-id9742.html

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326822539&siteId=291194637