Reprint Minister A masterpiece: Common sorting algorithm of JavaScript implementation
Note: This article is reproduced in the laboratory with the Mennwan Minister of the masterpiece, looking for internships to find work is imminent, this article is quite useful! Source: http://www.cnblogs.com/ywang1724/p/3946339.html#3037096. O (∩_∩) o~ intellectual property belongs to the minister's original.
Written interview often involves a variety of algorithms, this article briefly introduces some commonly used algorithms, and implemented with JavaScript.
1. Insert Sort
1) Introduction to Algorithms
The algorithm description of Insert sort (insertion-sort) is a simple and intuitive sorting algorithm. It works by constructing an ordered sequence, for unsorted data, to scan from backward forward in the sorted sequence, to find the appropriate position and insert it. The insertion sort is implemented on an implementation, usually in the order of In-place (that is, the ordering of extra space using only O (1), so that in the backward-forward scanning process, the ordered elements need to be moved back and forth gradually, providing the insertion space for the newest elements.
2) algorithm description and implementation
In general, the insertion sort is implemented using In-place on the array. The specific algorithm is described as follows:
- Starting with the first element, the element can be thought to have been sorted;
- Takes the next element and scans the sequence of elements that have been sorted from the back forward;
- If the element (sorted) is greater than the new element, move the element to the next position;
- Repeat step 3 until you find the sorted element is less than or equal to the position of the new element;
- After inserting a new element into the position;
- Repeat step 2~5.
JavaScript code implementation:
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 arr Ay[j + 1] = Array[j]; 8 j--; 9 }10 array[j + 1] = key;11 }12 return array;13 } else { return ' array is not An array! '; }16}
3) algorithm Analysis
- Best case: The input array is sorted in ascending order. T (n) = O (n)
- Worst case: Input arrays are sorted in descending order. T (n) = O (n2)
- Average condition: T (n) = O (n2)
Two or two points insert sort
1) Introduction to Algorithms
Binary insertion (binary-insert-sort) Sorting is a sort algorithm that makes small changes on the direct insertion sorting algorithm. The biggest difference between its and the direct insertion sorting algorithm is that it uses a binary search method to find the insertion position, and has a certain increase in speed.
2) algorithm description and implementation
In general, the insertion sort is implemented using In-place on the array. The specific algorithm is described as follows:
- Starting with the first element, the element can be thought to have been sorted;
- Takes the next element and finds the position of the first larger number in the sequence of ordered elements;
- After inserting a new element into the position;
- Repeat these two steps.
JavaScript code implementation:
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 <= R ight) {6 var middle = parseint ((left + right)/2), 7 if (Key < Array[middle]) {8 Right = middle-1; 9
} else {ten left = middle + 1;11 }12 }13 for (var j = i-1; J >= left; j--) {array[j + 1] = array[j];15 }16 array[left] = key;17 }18 return array;19 } else { return ' array is Not an array! '; }22}
3) algorithm Analysis
- Best case: T (n) = O (Nlogn)
- Worst case: T (n) = O (n2)
- Average condition: T (n) = O (n2)
Iii. Choice of sorting
1) Introduction to Algorithms
Select Sort (selection-sort) is a simple and intuitive sorting algorithm. It works by first finding the smallest (large) element in the unordered sequence, holding it to the starting position of the sort sequence, and then continuing to find the smallest (large) element from the remaining unsorted elements, and then dropping it to the end of the sorted sequence. And so on until all elements are sorted.
2) algorithm description and implementation
The direct selection of n records can be sorted by n-1 direct selection to get an ordered result. The specific algorithm is described as follows:
- Initial state: Unordered area is R[1..N], ordered area is empty;
- At the beginning of the first sequencing (i=1,2,3...n-1), the current ordered and unordered regions are r[1..i-1] and R (I.) respectively. N). This sort of sorting from the current unordered area to select the smallest key record r[k], and the 1th record of the unordered zone R Exchange, so that r[1..i] and R[I+1..N) respectively to increase the number of records added to a new ordered area and the number of records reduced by 1 new unordered regions;
- N-1 the end of the trip, the array is ordered.
JavaScript code implementation:
1 function selectionsort (array) {2 if (Object.prototype.toString.call (array). Slice (8,-1) = = = ' array ') {3 var l En = 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 { N-return ' array is not a array! '; }19}
3) algorithm Analysis
- Best case: T (n) = O (n2)
- Worst case: T (n) = O (n2)
- Average condition: T (n) = O (n2)
Four, bubble sort
1) Introduction to Algorithms
Bubble sort is a simple sort algorithm. It repeatedly visits the sequence to sort, compares two elements at a time, and swaps them if they are in the wrong order. The work of the sequence of visits is repeated until no more need to be exchanged, that is, the sequence is sorted. The algorithm is named because the smaller elements will slowly "float" through the switch to the top of the sequence.
2) algorithm description and implementation
The specific algorithm is described as follows:
- Compares the adjacent elements. If the first one is larger than the second, swap them two;
- For each pair of adjacent elements to do the same work, from the beginning of the first pair to the end of the last pair, so that the final element should be the largest number;
- Repeat the above steps for all elements except the last one;
- Repeat steps until the sort is complete.
JavaScript code implementation:
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 { return ' array is not a array! '; }17}
3) algorithm Analysis
- Best case: T (n) = O (n)
- Worst case: T (n) = O (n2)
- Average condition: T (n) = O (n2)
V. Quick Sort
1) Introduction to Algorithms
The basic idea of quick sorting: to separate the pending records into two separate parts by a single pass, in which some of the recorded keywords are smaller than the other, the two parts of the record can be sorted separately to achieve the order of the whole sequence.
2) algorithm description and implementation
Quick sort use the divide-and-conquer method to divide a string (list) into two substrings (sub-lists). The specific algorithm is described as follows:
- Select an element from the series, called the "Datum" (pivot);
- Reorder the columns, where all elements are placed in front of the datum in a smaller position than the base value, and all elements are larger than the base value behind the datum (the same number can be on either side). After the partition exits, the datum is in the middle of the sequence. This is called partition (partition) operation;
- recursively (recursive) sorts sub-columns that are smaller than the base value elements and sub-columns that are larger than the base value elements.
JavaScript code implementation:
1//Method 12 function QuickSort (array, left, right) {3 if (Object.prototype.toString.call (array)). Slice (8,-1) = = = ' Arra Y ' && 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); QuickSort (array, i + 1, righ t);};17} else {return ' array is not a array or left or right is not a number! '; *}20} var aaa = [3, 5, 2, 9, 1];22 QuickSort (AAA, 0, aaa.length-1); Console.log (AAA); 24 25 26//method 227 var Q Uicksort = function (arr) {arr.length <= 1) {return arr;} var pivotindex = Math.floor (arr.length /2); var pivot = Arr.splice (pivotindex, 1) [0];31 var left = [];32 var right = [];33 for (var i = 0; i < arr . length; i++) {Arr[i] < pivot) {Left.push (arr[i]); (Right.push} else {PNs Arr[i] 38}39}40 Return QuickSort (left). Concat ([pivot], QuickSort (right)); 41};
3) algorithm Analysis
- Best case: T (n) = O (Nlogn)
- Worst case: T (n) = O (n2)
- Average condition: T (n) = O (Nlogn)
Vi. sequencing of Heaps
1) Introduction to Algorithms
Heap ordering (heapsort) refers to a sort algorithm designed using the data structure of the heap. A heap is a structure that approximates a complete binary tree and satisfies the properties of the heap at the same time: that is, the key value or index of the child node is always less than (or greater than) its parent node.
2) algorithm description and implementation
The specific algorithm is described as follows:
- The initial sequence of keywords to sort (r1,r2 .... Rn) is constructed into a large top heap, which is the initial disordered zone;
- Swap the top element of the heap r[1] with the last element R[n] to get a new unordered area (R1,R2,...... RN-1) and the new ordered area (Rn), and satisfies the r[1,2...n-1]<=r[n];
- Because the new heap top r[1] may violate the nature of the heap, it requires a current unordered zone (R1,R2,...... RN-1) adjusts to the new heap, then swaps the r[1] with the last element of the unordered zone, resulting in a new unordered area (R1,R2 ...). Rn-2) and the new ordered area (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 complete.
JavaScript code implementation:
1/* Method Description: Heap sort 2 @param array to sort arrays */3 function Heapsort (array) {4 if (Object.prototype.toString.call (AR Ray). Slice (8,-1) = = = ' Array ') {5//Build heap 6 var heapsize = array.length, temp; 7 for (var i = Math.f Loor (HEAPSIZE/2)-1; I >= 0; i--) {8 heapify (array, I, heapsize), 9}10 11//Heap sort for (var j = heapsize- 1; J >= 1; j--) {temp = array[0];14 array[0] = array[j];15 array[j] = temp;16 heap Ify (array, 0,--heapsize);}18} else {return ' array is not a array! '; 20}21}22/* Method Description: The nature of the maintenance heap @param arr array @param x array subscript @param len Heap size */26 function heapify (arr, x, Len) {27 if (Object.prototype.toString.call (arr). Slice (8,-1) = = = ' Array ' && typeof x = = ' number ') {var L = 2 * x + 1, r = 2 * x + 2, largest = x, temp;29 if (L < len && Arr[l] > Arr[largest]) {30 largest = l;31}32 if (R < len && Arr[r] > arr[largest]) {largest = R;34 }35 if (Largest! = x) {$ temp = arr[x];37 Arr[x] = arr[largest];38 arr[l Argest] = temp;39 heapify (arr, largest, Len), +}41} else {A. Or x is not a number! '; 43}44}
3) algorithm Analysis
- Best case: T (n) = O (Nlogn)
- Worst case: T (n) = O (Nlogn)
- Average condition: T (n) = O (Nlogn)
Vii. Merge Sort
1) Introduction to Algorithms
Merge sort is an efficient sorting algorithm based on the merging operation. This algorithm is a very typical application of the partition method (Divide and Conquer). Merge sort is a stable sort method. The ordered Subsequence is merged to obtain a fully ordered sequence, i.e., the order of each subsequence is ordered, and then the sequence of sub-sequences is ordered. If you combine two ordered tables into an ordered table, it is called a 2-way merge.
2) algorithm description and implementation
The specific algorithm is described as follows:
- The input sequence of length n is divided into two sub-sequences of length n/2;
- The two sub-sequences were sorted by merging;
- Merges two sorted sub-sequences into a final sort sequence.
JavaScript code implementation:
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) {Ten var n1 = Q-p + 1, n2 = r-q, left = [], right = [], m = n = 0;11 for (var i = 0; i < N1; i++) {left[i ] = array[ p + i];13 }14 for (var j = 0, J < N2; J + +) { Right[j] = array[q + 1 + j];16}17 left[n1 ] = ri GHT[N2] = number.max_value;18 for (var k = p; k <= R; k++) { if (Left[m] <= right[n]) { array[k] = left[m];21 m++;22 } else { array[k] = right[n];24 n++;25}26 }27}
3) algorithm Analysis
- Best case: T (n) = O (n)
- Worst case: T (n) = O (Nlogn)
- Average condition: T (n) = O (Nlogn)
Eight, barrel sorting
1) Introduction to Algorithms
Bucket sorting (bucket sort) works: 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 a different sorting algorithm or recursively continue to sort by using the 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 bucket one by one;
- Sort each bucket that is not empty;
- From a bucket that is not empty, stitch up the sorted data.
JavaScript code implementation:
1/* Method Description: Bucket sort 2 @param array array 3 @param number of num 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); (var i = 1; i < Len; i++) {One min = min <= A Rray[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 + +) {var index = Math.floor ((array[j]-min)/space), + if (Buckets[index]) {//Non-empty bucket, insert sort ~ var k = Buckets[index ].length-1;19 while (k >= 0 && buckets[index][k] > Array[j]) {Buckets[index ][k + 1] = buckets[index][k];21 k--;22}23 buckets[index][k + 1] = array[j];24 } else {//empty bucket, initialization 25 Buckets[index] = [];26 buckets[index].push (Array[j]),}28}29 while (n < num) {result = Result.concat (Buckets[n]); n++;32}33 return result;34}
3) algorithm Analysis
Bucket sorting is best used with linear time O (n), and the time complexity of bucket sequencing depends on the time complexity of sorting the data between buckets, because the time complexity of the other parts is O (n). Obviously, the smaller the bucket, the less data between buckets, and the less time it takes to sort. But the corresponding space consumption will increase.
Nine, counting sort
1) Introduction to Algorithms
The Count sort (counting sort) is a stable sorting algorithm. The count sort uses an extra array of C, where the I element is the number of elements in the array A to be sorted with the value equal to I. The elements in a are then ranked in the correct position according to the 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;
- The number of occurrences of each element in the statistic array that is I, in the array C;
- Summation of all counts (starting with the first element in C, each item and the previous one);
- Reverse-Populate the target array: Place each element I in the C (i) of the new array, minus 1 for each element that is placed.
JavaScript code implementation:
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), }11 for (var K = len-1; K >=0; k--) { b[c[array[k]]-1] = array[k];13 c[array[k]]--;14 }15 return b;16}
3) algorithm Analysis
When the input element is an integer of n 0 to K, its run time is O (n + k). The count sort is not a comparison sort, and the sort is faster than any comparison sort algorithm. Because the length of the array C used to count depends on the range of data 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 the count sort for arrays with a large data range, which requires a lot of time and memory.
Reprint Minister A masterpiece: Common sorting algorithm of JavaScript implementation