9 large sorting algorithms implemented by JavaScript

Source: Internet
Author: User

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:

    1. Starting with the first element, the element can be thought to have been sorted;
    2. Takes the next element and scans the sequence of elements that have been sorted from the back forward;
    3. If the element (sorted) is greater than the new element, move the element to the next position;
    4. Repeat step 3 until you find the sorted element is less than or equal to the position of the new element;
    5. After inserting a new element into the position;
    6. 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

    • 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:

    1. Starting with the first element, the element can be thought to have been sorted;
    2. Takes the next element and finds the position of the first larger number in the sequence of ordered elements;
    3. After inserting a new element into the position;
    4. Repeat these 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 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:

    1. Initial state: Unordered area is R[1..N], ordered area is empty;
    2. 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;
    3. N-1 the end of the trip, 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 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:

    1. Compares the adjacent elements. If the first one is larger than the second, swap them two;
    2. 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;
    3. Repeat the above steps for all elements except the last one;
    4. Repeat steps until the sort 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

    • 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:

    1. Select an element from the series, called the "Datum" (pivot);
    2. 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;
    3. 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:

//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 = ar Ray[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 a 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 Two
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 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:

    1. The initial order-to-sort keyword sequence (r1,r2....rn) is constructed into a large top heap, which is the initial unordered area;
    2. 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];
    3. 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 a 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:

/* Method Description: Heap Sort
@param array to sort arrays */
function Heapsort (array) {
if (Object.prototype.toString.call (array). Slice (8,-1) = = = ' array ') {
Build a heap
var heapsize = array.length, temp;
for (var i = Math.floor (HEAPSIZE/2), I >= 0; I –) {
Heapify (Array, I, heapsize);
}

Heap Sort
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! ';
}
}
/* Method Description: Maintaining the nature of the heap
@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 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:

    1. The input sequence of length n is divided into two sub-sequences of length n/2;
    2. The two sub-sequences were sorted by merging;
    3. Merges two sorted sub-sequences into a final sort 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)
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:

    1. Set a quantitative array as an empty bucket;
    2. Traverse the input data, and put the data into the corresponding bucket one by one;
    3. Sort each bucket that is not empty;
    4. From a bucket that is not empty, stitch up the sorted data.

JavaScript code implementation:

/* Method Description: Bucket sort
@param array Arrays
Number of @param num barrels */
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]) {//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

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:

    1. Find the largest and smallest elements in the array to be sorted;
    2. The number of occurrences of each element in the statistic array that is I, in the array C;
    3. Summation of all counts (starting with the first element in C, each item and the previous one);
    4. 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:

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 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.

9 large sorting algorithms implemented by JavaScript

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.