JavaScript implements a variety of sorting algorithms _javascript skills

Source: Internet
Author: User

Written interview often involves a variety of algorithms, this article briefly introduces some commonly used algorithms, and JavaScript implementation.

1. Insert Sort

1) Introduction to the algorithm

The algorithm description of insertion sort (insertion-sort) is a simple and intuitive sort algorithm. It works by building an ordered sequence, scanning the sorted sequence for unsorted data, and finding the location and inserting it. Insert sorting on implementation, usually using in-place sorting (that is, just use the extra space of O (1) to sort), and in the process of backward scanning, you need to repeatedly move the sorted elements backwards and forwards, providing insert space for the newest elements.

2) algorithm description and implementation

In general, the insertion sort is implemented on an array using In-place. The specific algorithm is described as follows:

Starting with the first element, the element can be considered to have been sorted;
Take out the next element and scan forward from the back in the sorted sequence of elements;
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 element is less than or equal to the new element;
Inserts a new element into the location;
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 isn't ' an
    array! ';
  }
}

3) algorithm Analysis

Best case: The input array is sorted in ascending order. T (n) = O (n)
Worst case: The input array is sorted in descending order. T (n) = O (n2)
Average condition: T (n) = O (n2)
two or two-point insertion sort

1) Introduction to the algorithm

Binary insertion (binary-insert-sort) sequencing is a sort algorithm that makes small changes in the direct insertion sort algorithm. The most important difference with the direct insertion sorting algorithm is to find the insertion position using the binary search method, and there is a certain increase in speed.

2) algorithm description and implementation

In general, the insertion sort is implemented on an array using In-place. The specific algorithm is described as follows:

Starting with the first element, the element can be considered to have been sorted;
Takes out the next element, in the sorted sequence of elements, finds the position of the first number larger than it;
Inserts a new element into the location;
Repeat the two steps above.
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 isn't ' an
    array! ';
  }
}

3) algorithm Analysis

Best case: T (n) = O (Nlogn)
Worst case: T (n) = O (n2)
Average condition: T (n) = O (n2)
Third, select the sort

1) Introduction to the algorithm

Select Sort (selection-sort) is a simple and intuitive sort algorithm. How it works: First find the smallest (large) element in the unordered sequence, hold it to the starting position of the sort sequence, and then continue to look for the smallest (large) element from the remaining unordered elements and place it at the end of the sorted sequence. And so on until all the elements are sorted.

2) algorithm description and implementation

The direct selection of n records can be sorted by n-1 and ordered results. The specific algorithm is described as follows:

Initial state: Disordered region is R[1..N], the ordered region is empty;
At the start of the I-trip sort (i=1,2,3...n-1), the current ordered and unordered regions are r[1..i-1] and R (I.. N). The trip sort selects the smallest key word record r[k] from the current disordered area, and transforms it to the 1th record R exchange with the disordered region, so that the r[1..i] and R[I+1..N) become the new ordered region with the number of records added and the number of records reduced by 1.
N-1 the end of the trip, the array 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 isn't ' 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 the algorithm

Bubble sort is a simple sort algorithm. It repeatedly visits the sequence to be sorted, compares two elements at a time, and swaps them if they are in a wrong order. The task of visiting the series is repeated until no further exchange is needed, which means that the sequence has been sorted. The algorithm is named because the smaller elements float slowly through the exchange to the top of the sequence.

2) algorithm description and implementation

The specific algorithm is described as follows:

Compare the adjacent elements. If the first one is larger than the second one, exchange them for 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 in 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 sort completes.
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 isn't ' an
    array! ';
  }
}

3) algorithm Analysis

Best case: T (n) = O (n)
Worst case: T (n) = O (n2)
Average condition: T (n) = O (n2)
Five, quick sort

1) Introduction to the algorithm

The basic idea of a quick sort: to separate the rows of records into two separate parts by a single pass, where some of the records have less keywords than the other, you can sort the records separately to get the entire sequence sorted.

2) algorithm description and implementation

A quick sort uses divide-and-conquer methods to divide a string (list) into two substrings (sub-lists). The specific algorithm is described as follows:

Pick an element from a sequence called a "benchmark" (pivot);
Reorder the series, all elements smaller than the base value placed in front of the datum, 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 positioned in the middle of the series. This is called partition (partition) operation;
recursively (recursive) sorts the substrings that are less than the datum elements and those that are larger than the datum values.
JavaScript code implementation:

 Method A 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[rig
      HT], 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 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. Heap Sequencing

1) Introduction to the algorithm

Heap Ordering (heapsort) is a sort algorithm designed by using the data structure of a heap. Accumulation is the structure of an approximate complete binary tree, and it satisfies the nature of the accumulation: the key value or index of a child node is always less than (or greater than) its parent.

2) algorithm description and implementation

The specific algorithm is described as follows:

The initial sequence of key sequences to be sorted (r1,r2 ...). Rn) is constructed into a large top heap, which is the initial disordered region;
Swap the heap top element r[1] with the last element R[n] to get the new unordered area (R1,R2,...... RN-1) and the new ordered region (RN), and satisfy the r[1,2...n-1]<=r[n];
Because the new heap top r[1] may violate the nature of the heap after swapping, the current unordered area (R1,R2,...... Rn-1) is adjusted to the new heap, and then again R[1] is exchanged with the last element of the unordered area to get the new unordered area (R1,R2 ...). Rn-2) and a new ordered region (RN-1,RN). Repeat this process until the number of elements in the ordered area is n-1, the entire sort process completes.
JavaScript code implementation:

 /* Method Description: Heap sort @param array to be sorted/function Heapsort (array) {if Object.prototype.toString.call (array). Slice (8,-
    1 = = = ' Array ') {//Jian Yu 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);
  The else {return ' array isn't ' an array! '; }/* Method Description: The nature of the maintenance heap @param arr array @param x array subscript @param len Heap Size/function heapify (arr, x, len) {if (Object.prototype.toS Tring.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 are 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 the algorithm

Merge ordering is an effective sorting algorithm based on merging operation. The algorithm is a very typical application of the partition method (Divide and Conquer). Merge ordering is a stable sort method. The ordered Subsequence is merged to obtain a fully ordered sequence, that is, the sequence of each subsequence is ordered, and then the sequence between the subsequence segments is ordered. If the two ordered table is merged into an ordered table, it is called 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 n/2 sequences of length;
The two subsequence sequences were sorted by merging.
Merges two sorted 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, bucket sort

1) Introduction to the algorithm

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

2) algorithm description and implementation

The specific algorithm is described as follows:

Set a quantitative array as an empty bucket;
Traversing the input data and putting the data one by one into the corresponding bucket;
Sorting each bucket that is not empty;
Stitching up the sorted data from a bucket that is not empty.
JavaScript code implementation:

 /* Method Description: Bucket sort @param array @param number of num 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]) {//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 sort best uses the linear time O (n), the time complexity of the bucket sort, depending on the time complexity of sorting the data between the buckets, because the time complexity of the other parts is O (n). Obviously, the smaller the bucket, the smaller the data between the buckets, and the less time it takes to sort. But the corresponding space consumption will increase.

Nine, counting sort

1) Introduction to the algorithm

The counting sort (counting sort) is a stable sort 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 to the value equal to I. Then arrange the elements in a to the correct position based on 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;
Count the number of occurrences of an element in the array, in the first item of the array C;
Add to all counts (starting with the first element in C and adding each item to the previous one);
Reverse-Populate the target array: Place each element I in the new array in subparagraph C (i), subtracting C (i) from each element by 1.
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 between n 0 to K, its elapsed time is O (n + k). The count sort is not a comparison sort, and the order is faster than any comparison sort algorithm. Because the length of the array C used to count depends on the range of the 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 counting order a large amount of time and memory required for a large array of data.

The above is about the common JavaScript sorting algorithm of the entire content, I hope to help you learn.

Related Article

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.