JavaScript implementation and explanation of sorting algorithm (99JS notes) _javascript tips

Source: Internet
Author: User
Tags array length benchmark

Bubble sort

The principle of bubbling is to "float" the maximum element or the smallest element.

Insert Sort, select sort, quick sort, bubble sort are all comparison sort

Ideas

In turn, compare the adjacent two numbers, place the decimal number in front, and the large numbers in the back.

Step1: Compares the 1th and 2nd numbers, puts the decimal digits before the number, and puts the large numbers behind. Compare the 2nd and 3rd numbers, put the decimal places before the large number, so continue until the last two, the number of decimal places before the large number of put.
Step2: On the second trip: still starting from the first logarithm (since it could be due to the exchange of the 2nd number and the 3rd number, so that the 1th number is no longer less than the 2nd number, the decimal place before, after the large number, has been compared to the penultimate number (the first in the last position is already the largest), the second end, To get a new maximum number (in fact, the second largest number in the whole series) in the penultimate position.
So go on, repeat the process until you finish sorting.
Because the decimal is always pushed forward in the sort process, the large number is placed backward, which is the equivalent of a bubble going up, so called bubble sort.
Animation effects of bubble sort

Implementation: This piece of code is relatively simple, is the most basic algorithm in the foundation of the most basic code ...
Pay attention to three.

1. The method of exchanging classes can be solved in JavaScript using a very ingenious method of a=[b,b=a][0.
Replace

Copy Code code as follows:

Var,a,b,temp
temp = A;
A=b;
b = Temp

This Exchange method
2. Note the cache of the loop variable, which caches the Array.Length
3. Note that the embedded loop, from the first number to the penultimate n number, n is the comparison of the number of the step

function Bubblesort (array) {
var l=array.length;
for (var i = 0; i < L (i++) {//Comparison of the number of the length of the array for
(var j = 0; J < L-i + +) {//The number of inline exchanges is from the first number to the last total length-n number, n is the comparison s TEP number
if (Array[j] < array[j-1]) {
array[j] = [array[j-1], array[j-1] = array[j]][0]//here to exchange elements
}
}< C8/>for (var k = 0; k < l; k++) {
console.log (Array[k] + ",");
}
Console.log (' This is the first ' + (i+1) + ' sub Sort '
)
}
var a = [6,54,6,22,5,7,8,2,34];
Bubblesort (a);

Animation effects

Insert sort (Insertion sort)
very simple, that is, we touch the cards card steps!
Ideas:

1 First assume that we touch a card, we hand all the cards are set to Empty = [] touched a push (arr[0])
2 Remove the next card, set to a, in all our cards empty (has been sorted) from the forward scan
3 If the hand of this card empty[empty.length-n] (sorted) is greater than the new element, move the card to the next position (space) empty[empty.length-n]= empty[empty.length-n+1]
4 Repeat step 3 until you find the ordered card Empty[empty.length-n] less than or equal to a
5 Insert a in the position empty[empty.length-n]=a
6 Repeat step 2
But the JavaScript code is a little bit more difficult to implement, as follows:

function Insert (arr) {
var L = arr.length;
var empty = [];//empty array, representing our hand
Empty.push (arr[0]);//We first touch a for
(var i = 1; i < L; i++) {//Note that the starting point here is 1, because we have touched one!
if (Arr[i] > Empty[empty.length-1]) {
empty[empty.length] = arr[i]
}//If larger than ordered array empty, drop directly to end for
( var j = empty.length; J > 0 && arr[i] < empty[j-1]; j--) {//from the maximum value compared with ARR, in order to give Arr vacated. When you arr< an ordered array, you don't have to move.
Empty[j] = empty[j-1];//Move Right
empty[j-1] = arr[i];//Put value in vacated position//console.log
(empty)
}< C14/>return Empty
}

Then the important point of knowledge here is the && symbol, meaning "and", that is, both sides of the conditions must be satisfied, the expression was established.
The && symbol can also be substituted for if if (a) {fun ()} equals a&&b
The other one is very important.
Set Array is arr, then his "last item" is arr[arr.length-1].

Sort Animation


Select sort (Selection sort)
is also a simple sorting algorithm.

Ideas:

Find the smallest element-throw it in the array-and find the small-throw it into the array, and so on.
First find the smallest element in an unordered array, and find a way to make use of the means of constant judgment and assignment, that is, to set the first element of the array array[0] as the smallest element, then the "smallest element" in the array is the ordinal number of 0
After traversing the array, if the second element of the array is smaller than he is, then the second is the smallest element, and the "0" is updated to "1".
After the traversal, we know that the smallest element of this series is labeled "N"; take it directly to the starting position of the sort sequence (Array[n])
Then, continue to look for the smallest element from the remaining unsorted elements and place it at the end of the sort sequence. Notice that the subscript for the traversal begins at 1. Because we've picked out a minimum element.
And so on until all the elements are sorted.

function Selectsort (array) {
var min;
var L = array.length;//Cache length for
(var i = 0; i < l i++) {//start loop, Total loop l times, you can find l element
min = i;//Assume the first is the minimum element
fo R (var j = i + 1; j < L; j + +) {//() from the first start loop, traverse
if (Array[min] > Array[j])//To determine whether or not to
update the "minimum" subscript 
   }
if (min!= i) {//here because it is in the same array of operations, so direct exchange of elements can be. For example, the first item in the array is I, then I find the smallest element as array[min], then I need to exchange this min with I. Analogy
array[i]= [array[min],array[min]=array[i]][0];//interchange Element
}
}
return array;
}

Still note here is the exchange of the writing array[i]= [array[min],array[min]=array[i]][0]
can be convenient to the array[i] and Array[min] Exchange ~

Sort Animation

Quick Sort

The fast sort is the most powerful sorting algorithm, and the algorithm utilizes the recursive idea.

Ideas

Select an element from an array, called a "datum", which can be directly selected using LENGTH/2.
Traversing an array, all elements are placed in front of the datum smaller than the datum, and all elements are larger than the datum values behind the datum (the same number can be on either side). Popular: Male station to the left, women stand on the right.
We then got an array of such an array of array= than the smaller part of the Datum larray+ the base + of the large part of the base Rarray.
Then we just need to do the "Same" Larray,rarray.
This requires a recursive formulation. After processing, the Larray is divided into the Larray benchmark, smaller than the Larray benchmark, larger than the Larray benchmark.
Then we continue to operate, male station to the left, women stand on the right.
Until we found out that the length of the Larray was 1, not enough to divide it, and we thought the sort ended.

function QuickSort (arr) {
var L = arr.length;//Cache Array length if
(arr.length <= 1) {return arr};//If we get the Larray, Rarray length is smaller than 1, then no need to row ~
var num = Math.floor (ARR.LENGTH/2);//Take the number in the middle of the array. Note that LENGTH/2 is not necessarily an integer, Math.floor the whole
var numvalue = Arr.splice (num, 1) [0];//Use the Splice method, take an element out, pay attention to the syntax
var left = [];/ /Create Left Datum container
var right = [];//to create the right-hand datum container for
(var i = 0; i < L + = 1) {//start traversing array
arr[i] < NumValue? left.pu SH (arr[i]): Right.push (Arr[i]);//male station left, female station right.
}
Return quickSort. Concat ([NumValue], QuickSort (right))//recursively, continue to operate on the left and right arrays.
}

Animation effect:

Notice here Arr.splice (num,1) Although only a few, but splice result is also an array, need [0], otherwise the result will be very wonderful to appear a bunch of array (1) of the arrays ...
Splice's Reference: http://www.jb51.net/w3school/js/jsref_splice.htm
Math.floor is the reference http://www.jb51.net/w3school/js/js_obj_math.htm of the Math object
What is recursion: http://baike.baidu.com/view/96473.htm

The above four algorithms in addition to fast sorting, are simple sorting algorithm, and these four algorithms in the interview are very frequent exam ~
Here still want to emphasize that, the above algorithm uses a lot of circulation and the relevant knowledge of the array, must memorize!

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.