JavaScript Implementation of Common sorting algorithms
The written test interview often involves various algorithms. This article briefly introduces some common algorithms and uses JavaScript to implement them. 1. Insert sorting 1) Algorithm 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 generally, insert sorting is implemented on the array using in-place. The specific algorithm description is as follows: starting from the first element, this element can be considered to have been sorted; the next element is retrieved and scanned from the back to the front in the sorted element sequence; if the element (sorted) is greater than the new element, move it to the next position. Repeat Step 3 until you find the position where the sorted element is smaller than or equal to the new element; insert the new element to this position. Repeat Step 2 ~ 5. JavaScript code implementation: Copy code 1 function insertionSort (array) {2 if (Object. prototype. toString. call (array ). slice (8,-1) ==== 'array') {3 for (var I = 1; I <Array. length; I ++) {4 var key = array [I]; 5 var j = I-1; 6 while (j> = 0 & array [j]> key) {7 array [j + 1] = array [j]; 8 j --; 9} 10 array [j + 1] = key; 11} 12 return array; 13} else {14 return 'array is not an array! '; 15} 16} copy code 3) optimal algorithm analysis: Input arrays are sorted 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 insertion sorting 1) algorithm Introduction Binary insertion (Binary-insert-sort) sorting is a sort algorithm that makes minor changes to the directly inserted sorting 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 generally, insert sorting is implemented on the array using in-place. The specific algorithm description is as follows: starting from the first element, this element can be considered to have been sorted; the next element is retrieved, in the sorted element sequence, find the first position that is greater than the first number. Insert the new element to the position. Repeat the preceding two steps. JavaScript code implementation: Copy code 1 function binaryInsertionSort (array) {2 if (Object. prototype. toString. call (array ). slice (8,-1) ==== 'array') {3 for (var I = 1; I <Array. length; I ++) {4 var key = array [I], left = 0, right = I-1; 5 while (left <= right) {6 var middle = parseInt (left + right)/2); 7 if (key <array [middle]) {8 right = middle-1; 9} else {10 left = middle + 1; 11} 12} 13 for (var j = I-1; j> = left; j --) {14 array [j + 1] = array [j]; 15} 16 array [left] = key; 17} 18 return array; 19} else {20 return 'array is not an array! '; 21} 22} copy code 3) optimal algorithm analysis: T (n) = O (nlogn) Worst Case: T (n) = O (n2) average: T (n) = O (n2) 3. Select sorting 1) Introduction to the algorithm 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 Direct selection and sorting of n records can be obtained through n-1. The specific algorithm is described as follows: Initial State: the unordered zone is R [1 .. n], the sorting area is empty; the I-th sorting (I =, 3... n-1) at the beginning, the current ordered and unordered areas 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 round ends and the array is ordered. JavaScript code implementation: Copy code 1 function selectionSort (array) {2 if (Object. prototype. toString. call (array ). slice (8,-1) ==='array') {3 var len = Array. length, temp; 4 for (var I = 0; I <len-1; I ++) {5 var min = array [I]; 6 for (var j = I + 1; j <len; j ++) {7 if (array [j] <min) {8 temp = min; 9 min = array [j]; 10 array [j] = temp; 11} 12} 13 array [I] = min; 14} 15 return array; 16} else {17 return 'a Rray is not an Array! '; 18} 19} copy code 3) optimal algorithm analysis: T (n) = O (n2) Worst Case: T (n) = O (n2) average: T (n) = O (n2) 4. Bubble Sorting 1) algorithm introduction 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 specific Algorithm Description: Compares adjacent elements. If the first one is bigger than the second one, exchange the two of them. perform the same work on each pair of adjacent elements, from the first pair to the last one at the end, in this way, the final element should be the largest number. Repeat the above steps for all elements except the last one. Repeat steps 1 ~ 3, until the sorting is completed. JavaScript code implementation: Copy code 1 function bubbleSort (array) {2 if (Object. prototype. toString. call (array ). slice (8,-1) ==='array') {3 var len = Array. length, temp; 4 for (var I = 0; I <len-1; I ++) {5 for (var j = len-1; j> = I; j --) {6 if (array [j] <array [j-1]) {7 temp = array [j]; 8 array [j] = array [j-1]; 9 array [j-1] = temp; 10} 11} 12} 13 return array; 14} else {15 return 'array is not Array! '; 16} 17} copy code 3) optimal algorithm analysis: T (n) = O (n) Worst Case: T (n) = O (n2) average: T (n) = O (n2) 5. Fast sorting 1) Basic Idea of fast sorting: sort the records to be sorted into two separate parts, if the keywords of some records are smaller than those of the other, you can sort the two records separately to achieve the sequence order. 2) algorithm description and quick sorting: Use the grouping method to divide a string (list) into two sub-strings (sub-lists ). The specific algorithm description is as follows: pick out an element from the series, called "benchmark"; reorder the series, all elements smaller than the benchmark value placed in front of the benchmark, all elements are placed behind the benchmark (the same number can reach any side ). After the partition exits, the benchmark is in the middle of the series. This is called the partition operation. recursively (recursive) sorts the subseries smaller than the reference value element and the subseries greater than the reference value element. JavaScript code implementation: Copy code 1 // method 2 function quickSort (array, left, right) {3 if (Object. prototype. toString. call (array ). slice (8,-1) ==== 'array' & typeof left === 'number' & typeof right === 'number ') {4 if (left <right) {5 var x = array [right], I = left-1, temp; 6 for (var j = left; j <= right; j ++) {7 if (array [j] <= x) {8 I ++; 9 temp = array [I]; 10 array [I] = array [j]; 11 array [j] = temp; 12} 13} 14 quickSort (array, left, I-1); 15 quickSort (array, I + 1, right); 16 }; 17} else {18 return 'array is not an array or left or right is not a number! '; 19} 20} 21 var aaa = [3, 5, 2, 9, 1]; 22 quickSort (aaa, 0, aaa. length-1); 23 console. log (aaa); 24 25 26 // method 2 27 var quickSort = function (arr) {28 if (arr. length <= 1) {return arr;} 29 var variable tindex = Math. floor (arr. length/2); 30 var rows = arr. splice (FIG, 1) [0]; 31 var left = []; 32 var right = []; 33 for (var I = 0; I <arr. length; I ++) {34 if (arr [I] <strong) {35 left. push (arr [I]); 36} e Lse {37 right. push (arr [I]); 38} 39} 40 return quickSort (left ). concat ([ignore], quickSort (right); 41}; copy code 3) optimal algorithm analysis: T (n) = O (nlogn) Worst Case: T (n) = O (n2) average: T (n) = O (nlogn) vi. Heap sorting 1) algorithm overview Heapsort) it is a sort algorithm designed by using the data structure such as 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 specific Algorithm Description: The initial sequence of keywords to be sorted (R1, R2 .... rn) is built into a large top heap, which is the initial unordered zone. The top element R [1] is exchanged with the last element R [n, in this case, a new unordered partition (R1, R2 ,...... rn-1) and the new ordered zone (Rn), and meet R [1, 2... n-1] <= R [n]; since the new stack top R [1] After switching may violate the stack nature, the 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: Copy code 1/* method Description: heapSort 2 @ param array to be sorted */3 function heapSort (array) {4 if (Object. prototype. toString. call (array ). slice (8,-1) ==='array') {5 // heap Building 6 var heapSize = Array. length, temp; 7 for (var I = Math. floor (heapSize/2); I> = 0; I --) {8 heapify (array, I, heapSize ); 9} 10 11 // heap sorting 12 for (var j = heapSize-1; j> = 1; j --) {13 temp = array [0]; 14 array [0] = array [j]; 15 array [j] = Temp; 16 heapify (array, 0, -- heapSize); 17} 18} else {19 return 'array is not an array! '; 20} 21} 22/* method description: maintain heap properties 23 @ param arr array 24 @ param x array subscript 25 @ param len heap size */26 function heapify (arr, x, len) {27 if (Object. prototype. toString. call (arr ). slice (8,-1) ==== 'array' & typeof x === 'number') {28 var l = 2 * x, r = 2 * x + 1, largest = x, temp; 29 if (l <len & arr [l]> arr [largest]) {30 largest = l; 31} 32 if (r <len & arr [r]> arr [largest]) {33 largest = r; 34} 35 if (largest! = X) {36 temp = arr [x]; 37 arr [x] = arr [largest]; 38 arr [largest] = temp; 39 heapify (arr, largest, len); 40} 41} else {42 return 'Arr is not an Array or x is not a number! '; 43} 44} copy code 3) optimal algorithm analysis: T (n) = O (nlogn) Worst Case: T (n) = O (nlogn) average: T (n) = O (nlogn) VII. Merge sort 1) algorithm overview merge sort is an effective sort algorithm built on the merge operation. 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 specific Algorithm Description: divides an input sequence with a length of n into two subsequences with a length of n/2, and uses Merge Sorting for the two subsequences respectively; combine two sorted subsequences into a final sorting sequence. JavaScript code implementation: Copy code 1 function mergeSort (array, p, r) {2 if (p <r) {3 var q = Math. floor (p + r)/2); 4 mergeSort (array, p, q); 5 mergeSort (array, q + 1, r); 6 merge (array, p, q, r); 7} 8} 9 function merge (array, p, q, r) {10 var n1 = q-p + 1, n2 = r-q, left = [], right = [], m = n = 0; 11 for (var I = 0; I <n1; I ++) {12 left [I] = array [p + I]; 13} 14 for (var j = 0; j <n2; j ++) {15 rig Ht [j] = array [q + 1 + j]; 16} 17 left [n1] = right [n2] = Number. MAX_VALUE; 18 for (var k = p; k <= r; k ++) {19 if (left [m] <= right [n]) {20 array [k] = left [m]; 21 m ++; 22} else {23 array [k] = right [n]; 24 n ++; 25} 26} 27} copy code 3) optimal algorithm analysis: T (n) = O (n) Worst Case: T (n) = O (nlogn) average: T (n) = O (nlogn) 8. Bucket sorting 1) algorithm overview the working principle of Bucket sort: assuming that the input data is evenly distributed, data is distributed to a limited number of buckets, and each bucket is sorted separately (it is possible to use another sort algorithm or use the recursive method to continue sorting buckets ). 2) algorithm description and implementation specific Algorithm Description: set a quantitative array as an empty bucket, traverse the input data, and put the data one by one in the corresponding bucket; sort each bucket that is not empty, and splice the sorted data from the bucket that is not empty. JavaScript code implementation: Copy code 1/* method Description: bucket sorting 2 @ param array 3 @ param num Number of buckets */4 function bucketSort (array, num) {5 if (array. length <= 1) {6 return array; 7} 8 var len = array. length, buckets = [], result = [], min = max = array [0], regex = '/^ [1-9] + [0-9] * $/', space, n = 0; 9 num = num | (num> 1 & regex. test (num ))? Num: 10); 10 for (var I = 1; I <len; I ++) {11 min = min <= array [I]? Min: array [I]; 12 max = max> = array [I]? Max: array [I]; 13} 14 space = (max-min + 1)/num; 15 for (var j = 0; j <len; j ++) {16 var index = Math. floor (array [j]-min)/space); 17 if (buckets [index]) {// non-empty bucket, insert sort 18 var k = buckets [index]. length-1; 19 while (k> = 0 & buckets [index] [k]> array [j]) {20 buckets [index] [k + 1] = buckets [index] [k]; 21 k --; 22} 23 buckets [index] [k + 1] = array [j]; 24} else {// empty bucket, initialize 25 buckets [index] = []; 26 Buckets [index]. push (array [j]); 27} 28} 29 while (n <num) {30 result = result. concat (buckets [n]); 31 n ++; 32} 33 return result; 34} copy code 3) use linear time O (n) to analyze bucket sorting ), 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) 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 specific Algorithm Description: Find the largest and smallest elements in the array to be sorted, and count the number of times each element with a value of I in the array appears, store the I entry of array C; accumulate all counts (starting from the first element in C, each of which is added to the previous one); reverse fill in the target array: place each element I in item C (I) of the new array, and subtract C (I) From 1 for each element. JavaScript code implementation: Copy code 1 function countingSort (array) {2 var len = array. length, B = [], C = [], min = max = array [0]; 3 for (var I = 0; I <len; I ++) {4 min = min <= array [I]? Min: array [I]; 5 max = max> = array [I]? Max: array [I]; 6 C [array [I] = C [array [I]? C [array [I] + 1: 1; 7} 8 for (var j = min; j <max; j ++) {9 C [j + 1] = (C [j + 1] | 0) + (C [j] | 0 ); 10} 11 for (var k = len-1; k> = 0; k --) {12 B [C [array [k]-1] = array [k]; 13 C [array [k] --; 14} 15 return B; 16}