This article mainly introduces information about various sorting algorithms implemented by JavaScript, including Bubble sorting, insertion sorting, and selection sorting. If you are interested, refer to the various algorithms frequently used in the test interview, this article briefly introduces some common algorithms and uses JavaScript to implement them.
1. Insert sorting
1) algorithm Overview
The description of Insertion-Sort is a simple and intuitive sorting algorithm. Its working principle is to build an ordered sequence. For unordered data, scan the sorted sequence from the back to the front, locate the corresponding position, and insert it. Insert sorting usually uses in-place sorting (that is, sorting of the extra space of O (1). Therefore, during the scanning from the back to the forward, the sorted elements need to be moved backward repeatedly to provide the insert space for the new elements.
2) algorithm description and implementation
In general, insert sorting 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;
Extracts the next element and scans it forward from the back in the sorted element sequence;
If the element (sorted) is greater than the new element, move the element to the next position;
Repeat Step 3 until you find the position where the sorted elements are smaller than or equal to the new elements;
Insert the new element to this position;
Repeat Step 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
Optimal Condition: Input arrays are arranged in ascending order. T (n) = O (n)
Worst case: the input array is sorted in descending order. T (n) = O (n2)
Average: T (n) = O (n2)
Ii. Binary insert sorting
1) algorithm Overview
Binary-insert-sort is a sort algorithm that makes minor changes to the directly inserted sort algorithm. The biggest difference between the direct insertion Sorting Algorithm and the direct insertion sorting algorithm is that binary search is used to find the Insertion Location, which improves the speed.
2) algorithm description and implementation
In general, insert sorting 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;
Extracts the next element and finds the first number greater than the sorted element sequence in binary mode;
Insert the new element to this position;
Repeat the preceding 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: T (n) = O (n2)
3. Select sorting
1) algorithm Overview
Selection-sort is a simple and intuitive sorting algorithm. Working principle: first, find the smallest (large) element in the unordered sequence and store it to the starting position of the sorting sequence. Then, then, find the smallest (large) element from the remaining unordered elements and put it at the end of the sorted sequence. And so on until all elements are sorted.
2) algorithm description and implementation
The Direct selection and sorting of n records can be directly selected and sorted through n-1 troughs to obtain the ordered results. The specific algorithm is described as follows:
Initial status: the disordered area is R [1. n], and the ordered area is empty;
Sequential I (I = 1, 2, 3... N-1) at the beginning, the current ordered zone and disordered zone are respectively R [1 .. I-1] and R (I.. n ). This sort field selects the record R [k] with the smallest keyword from the current unordered area and exchanges it with the R of the 1st records in the unordered area so that R [1 .. i] and R [I + 1 .. n) change to a new ordered area with one more record count and a new unordered area with one fewer record count;
N-1-1 stops, 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: T (n) = O (n2)
Iv. Bubble Sorting
1) algorithm Overview
Bubble Sorting is a simple sorting algorithm. It repeatedly visits the series to be sorted, compares two elements at a time, and exchanges them if their order is wrong. The work of visiting a sequence is repeated until there is no need for exchange, that is, the sequence has been sorted. The name of this algorithm comes from because the smaller elements will slowly "float" to the top of the series through the exchange.
2) algorithm description and implementation
The specific algorithm is described as follows:
Compares adjacent elements. If the first one is bigger than the second one, exchange the two;
Perform the same work on each adjacent element, starting from the first pair to the last pair at the end, so that the last element will be the largest number;
Repeat the preceding steps for all elements except the last one;
Repeat steps 1 ~ 3, until the sorting is completed.
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
Best case: T (n) = O (n)
Worst case: T (n) = O (n2)
Average: T (n) = O (n2)
5. Quick sorting
1) algorithm Overview
The basic idea of fast sorting: separates the records to be sorted into two separate parts by one sort. the keywords of some records are smaller than those of the other, then, the two records can be sorted separately to achieve the whole sequence order.
2) algorithm description and implementation
Quick sorting uses the grouping method to divide a string (list) into two substrings (sub-lists ). The specific algorithm is described as follows:
Picking an element from a series is called a benchmark );
Re-sort the series. All elements are placed before the benchmark values smaller than the benchmark values, and all elements are placed behind the benchmark values larger than the benchmark values (the same number can reach either side ). After the partition exits, the benchmark is in the middle of the series. This is called a partition operation;
Recursively (recursive) sorts the subseries smaller than the reference value element and the subseries larger than the reference value element.
JavaScript code implementation:
// Method 1 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 (ar Ray, 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); // method 2 var quickSort = function (arr) {if (arr. length <= 1) {return arr;} var variable tindex = Math. floor (arr. length/2); var partition = arr. splice (FIG, 1) [0]; var left = []; var right = []; for (var I = 0; I <arr. length; I ++) {if (arr [I] <distinct) {left. push (arr [I]);} else {right. push (arr [I]);} return quickSort (left ). concat ([progress], quickSort (right ));};
3) algorithm analysis
Best case: T (n) = O (nlogn)
Worst case: T (n) = O (n2)
Average condition: T (n) = O (nlogn)
6. Heap sorting
1) algorithm Overview
Heapsort is a sort algorithm designed by using the data structure of heap. Accumulation is a structure that is similar to a Complete Binary Tree and meets the accumulation nature: that is, the key value or index of a child node is always smaller than (or greater than) its parent node.
2) algorithm description and implementation
The specific algorithm is described as follows:
Build the sequence of initial keywords to be sorted (R1, R2.... Rn) into a large top heap, which is the initial unordered zone;
Swap the top element R [1] with the last element R [n] to obtain a new unordered zone (R1, R2 ,...... rn-1) and the new ordered zone (Rn), and meet R [1, 2... n-1] <= R [n];
Since the new heap top R [1] After switching may violate the heap nature, it is necessary for the current unordered zone (R1, R2 ,...... rn-1) adjusted to the new heap, and then re-exchange the R [1] with the last element of the unordered area, get the new unordered area (R1, R2 .... rn-2) and the new ordered zone (Rn-1, Rn ). Repeat this process until the number of elements in the ordered area is n-1, the entire sorting process is completed.
JavaScript code implementation:
/* Method Description: heap sorting @ param array to be sorted */function heapSort (array) {if (Object. prototype. toString. call (array ). slice (8,-1) ==='array') {// create a heap var heapSize = Array. length, temp; for (var I = Math. floor (heapSize/2); I> = 0; I --) {heapify (array, I, heapSize);} // heap sorting for (var j = heapSize-1; j> = 1; j --) {temp = array [0]; array [0] = array [j]; array [j] = temp; heapify (array, 0, -- heapSize) ;}} else {ret Urn' array is not an Array! ';}}/* Method Description: Maintain the heap nature @ param arr array @ param x array subscript @ param len heap size */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 condition: T (n) = O (nlogn)
VII. Merge Sorting
1) algorithm Overview
Merge Sorting is an effective Sorting Algorithm Based on merge operations. This algorithm is a very typical application of Divide and Conquer. Merge Sorting is a stable sorting method. Merges ordered subsequences to obtain a fully ordered sequence. That is, first orders each subsequence, and then orders the subsequence segments. If two ordered tables are merged into an ordered table, it is called a 2-way merge.
2) algorithm description and implementation
The specific algorithm is described as follows:
Divides an input sequence whose length is n into two subsequences whose length is n/2;
Merge the two subsequences;
Combine two sorted subsequences into a final sorting 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 condition: T (n) = O (nlogn)
8. Sort buckets
1) algorithm Overview
Working principle of Bucket sort: assume that the input data is evenly distributed and the data is distributed to a limited number of buckets, sort each bucket separately (it is possible to use another sort algorithm or use the recursive method to continue sorting buckets ).
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 place the data one by one in the corresponding bucket;
Sort buckets that are not empty;
Splice sorted data from buckets that are not empty.
JavaScript code implementation:
/* Method Description: bucket sorting @ param array @ Number of param num buckets */function bucketSort (array, num) {if (array. length 1 & regex. test (num ))? Num: 10); for (var I = 1; I <len; I ++) {min = 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]) {// non-empty bucket, insert sort 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 {// empty bucket, initialize buckets [index] = []; buckets [index]. push (array [j]) ;}}while (n <num) {result = result. concat (buckets [n]); n ++;} return result ;}
3) algorithm analysis
In the case of Bucket sorting, the linear time O (n) is used. the time complexity of Bucket sorting depends on the time complexity of sorting data between buckets, because the time complexity of other parts is O (n ). Obviously, the smaller the bucket division, the less data each bucket has, and the less time it takes to sort data. But the corresponding space consumption will increase.
9. Counting sorting
1) algorithm Overview
Counting sort is a stable sorting algorithm. Count sorting uses an additional array C, where element I is the number of elements whose A value is equal to I in the array to be sorted. Then, sort the elements in A to the correct position based on Array C. 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 times each element with the I value appears in the array, and store the I entry of array C;
Accumulate all counts (starting from the first element in C and adding each item to the previous one );
Backward filling of the target array: place each element I in item C (I) of the new array, and subtract 1 from each element.
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] ? 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 element is an integer between n 0 and k, its running time is O (n + k ). Counting sorting is not a comparative sorting, and the sorting speed is faster than any comparative sorting algorithm. Because the length of array C used to count depends on the data range in the array to be sorted (equal to the difference between the maximum and minimum values of the array to be sorted plus 1 ), this makes counting sorting a large amount of time and memory required for arrays with a large data range.
The above is the content of JavaScript to implement various sorting algorithms _ javascript skills. For more information, please follow the PHP Chinese Network (www.php1.cn )!