The most common sort of JS algorithm

Source: Internet
Author: User

Introduced

The years of university learning computer language, from C language, to C + +, to data structure java. I was most impressed with the first teacher to talk about the bubble algorithm, until now I graduated from the university, I gradually tongqiao. Just learn the front-end when the front-end is to make good-looking and dazzling page on the line, and then gradually learned that the front-end is not just the page Aberdeen. An American group interview, the interviewer said they want not only the front end, they want is "engineer", from the beginning of the interview to the end of the question is the algorithm, immediately hit me. Binary tree, basic algorithm and time complexity are very important things, not only embodies a front-end learning depth, but also embodies a computer students professional level. So, in order to check the gaps, I decided to start studying the program Ape's favorite algorithm, today to talk about the most commonly used sorting algorithm. Squid have seen a lot of information is too professional, do not understand, so I will try to use to let themselves (others) understand the introduction to describe it ~

Common sorting algorithms
    • Bubble sort (Bubble sort)

    Plain English Introduction : Compare the adjacent two number, if the back is smaller than the front, put the small one in front.

   Complexity of Time: O (n2)

Animated Demo : bubbling sort

    Actual code :

Method One:
function Bubblesort (arr) {for (Var i=0;i<arr.length-1;i++) {for (var j=0;j<arr.length-1;j++) { if ( Arr[j+1]<arr[j]) { temp = arr[j+1]; ARR[J+1] = arr[j]; ARR[J] = temp;}} } return arr;}

In contrast to subparagraphs j+1 and J of Arr, if subparagraph j+1 is less than subparagraph j, the j+1 and subparagraph j are exchanged. If the final order is not reached (from small to large), continue to find, continue to change, until the final effect is achieved

But the above method is not perfect, if the array is already ordered, there is no need to compare, so there is an optimized bubble sorting algorithm:

Optimized bubble sorting algorithm

Method two (optimization algorithm):
function Bubblesort (arr) { var flag = false; Define a variable to false, non-swapped position for (Var i=0;i<arr.length-1;i++) {for (var j=0;j<arr.length-1;j++) { if (arr[ J+1]<arr[j]) { temp = arr[j+1]; ARR[J+1] = arr[j]; ARR[J] = temp; Flag = true; True, the swapped position } if (flag) { flag = false;//If the position is swapped, flag is reset to False }else{break ; If not swapped, jump out of Loop } } return arr;}


Or write it like this ~
function Bubblesort (arr) {    var flag;    for (Var i=0;i<arr.length-1;i++) {        flag =false;        for (Var j=0;j<arr.length-1;j++) {            if (Arr[j+1]<arr[j]) {                temp = arr[j+1];                ARR[J+1] = arr[j];                ARR[J] = temp;                Flag = true;            }        }        if (!flag) {            return arr;        }     }    return arr;}

    • Select sort (Selection sort)

   Plain English: Select the smallest value in an array of random order, and then swap with the first bit of the array after each loop

   Complexity of Time:O (n2)

Animated Demo : Select Sort

Actual code:

var arr=[5,3,2,4,1,0];
function Findmin (arr,first) { var minindex = first; Define the minimum subscript var minnum = Arr[first];//define the minimum value in the array for (var i=first+1;i<arr.length;i++) {//loop to find the minimum and minimum subscript if ( Arr[i]<minnum) { minnum = arr[i]; Minindex = i; } }
Return minindex;//returns the minimum subscript for a total of six searches, with the minimum subscript: 5,4,2,4,4,5 } function Selectionsort (arr) {for ( var i=0;i<arr.length;i++) { var min =var temp = arr[min]; Arr[min] = Arr[i]; eg. first cycle: Swap min. 5 and Arr[0] for Exchange arr[i] = temp; The remaining several times with the first } return arr; } document.write (Selectionsort (arr)); 0,1,2,3,4,5,

Sort Process : (self-drawing of a rough box table to dislike)

    • Merge sort (mergesort)

    Plain English Introduction: Divides an array into two arrays, the left is ordered, the right is ordered, and then merged together to sort

Professional Introduction: Merge sort is a typical example of divide and conquer, which refers to the operation of merging two sorted sequences into a sequence.

Complexity of Time: O (NLOGN)

Animation Demo: Merge sort

Actual code:

     var arr=[-11,17,12,19,0,-222];         function MergeSort (arr,s,e) {if (s>e) {//start position is greater than end position, return empty array return []; }else if (s==e) {return [arr[s]];//start position equals end position, indicating that there is only one number in the array, return an array with only one number} var mindex = Math. Floor ((s+e)/2); The median position of index var ArrL = mergesort (Arr,s,mindex); The left array is sorted by var arrr = MergeSort (arr,mindex+1,e); Sort the array on the right to var resultarr = [];                 The result array while (Arrl.length>0 | | arrr.length>0) {//when the left and right two arrays are not empty if (Arrl[0]<arrr[0]) {             Resultarr.push (Arrl.shift ());             }else{Resultarr.push (Arrr.shift ());                 } if (arrl.length==0) {//When the left array is empty Resultarr = Resultarr.concat (ARRR);             Break                 }else if (arrr.length==0) {Resultarr = Resultarr.concat (ArrL);             Break     }} return Resultarr; } document.write (MergeSort (arr,0, arr.length-1)); 

  Sorting process:

    • Quick Sort (quickSort)

  Plain English Introduction: Quote Nanyi Teacher's sentence, feeling is very good understanding of ~ (My goal is to become like Nanyi teacher)

(1) In the dataset, select an element as the "datum" (pivot).

(2) All elements smaller than "datum" are moved to the left of "datum", and all elements that are greater than "datum" are moved to the right of "datum".

(3) for the two subsets to the left and right of the Datum, repeat the first and second steps until there is only one element left in all the subsets.  

Actual code:

    var arr=[77,-33,22,32,0,2,11];    function QuickSort (arr) {if        (arr.length<=1) {///If the array has only one digit, return an array of return            arr;        }        var mnumindex = Math.floor (ARR.LENGTH/2); Subscript        var mnum = Arr.splice ([mnumindex],1) [0] for reference value;  Take the benchmark value        var left = [];  Left-        hand array var right = [];/////////-the array for                (Var i=0;i<arr.length;i++) {            if (arr[i]<mnum) {  //If the array is less than the base value , placed on the left array                left.push (Arr[i]);            } else{                ///otherwise Right.push (Arr[i]);}        }                Return QuickSort (left). Concat ([Mnum],quicksort (right)); Returns the left array + datum value + right array    }    document.write (QuickSort (arr));

Sorting process:

The above is some of the common sort, but there are a lot of common sort did not mention ~ ~ Late will also write a common sort of two ~ please look forward to Oh ~ Hope I learned something can also help you ~ have said the wrong place to welcome criticism ~

The most common sort of JS algorithm

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.