JavaScript algorithm-sorting algorithm

Source: Internet
Author: User

? I will walk through this life, and never again. All the good deeds that are in your power, all the good intentions that are filled with heart, I will not hesitate to Pour. I will not delay, no longer indifferent, only because the road of this life, can never again.

The two most common operations performed on data stored in a computer are sorting and indexing. The following description of the sorting method, for the moment is used to test the array (small to large).

var dataAry = [543712869// 测试数组
/** *【工具方法】交换数组中两个值 * @param ary 数组 * @param i 下标i * @param j 下标j */function swap(ary, i, j) {    var temp = ary[i];    ary[i] = ary[j];    ary[j] = temp;}
Bubble sort

? This is called bubble ordering because when you use this sort algorithm, the data value floats from one end of the array to the other, like a bubble. For example, sort from small to large: it compares adjacent data and swaps them when the left value is greater than the right Value.

The bubbling sorting algorithm works as Follows: (from small to Large)

    1. Compares the adjacent Elements. If the first one is bigger than the second one, swap them both.
    2. Do the same for each pair of adjacent elements, starting with the last pair from the first pair to the End. At this point, the last element should be the maximum number.
    3. Repeat the above steps for all elements, except for the last One.
    4. Repeat the above steps each time for fewer elements, until there are no pairs of numbers to Compare.
f Unction  bubblesort   (dataary)  {    Span class= "hljs-keyword" >var  len = dataary.length; for  (var  i = 0 ; i < len; i++) {for  (var  j = 0; J < len-i;                J + +) {if  (dataary[j] > Dataary[j+1 ]) {            Swap (dataary, j, j+1 ); }}} return  dataary;} //test  console.log (bubblesort (dataary)); //[1, 2, 3, 4, 5, 6, 7, 8, 9]   
Select sort

? Compares the first data to other data, starting with the first data in the Array. It works by selecting the smallest (or largest) data from the data to be sorted, and storing it at the beginning of the sequence until all the data elements are sorted Out.

function selectionSort(dataAry) {    var len = dataAry.length;    for(var01; i++) {        for(var1; j < len; j++) {            if(dataAry[i] > dataAry[j]) {                swap(dataAry, i , j);            }        }    }    return dataAry;}// 测试// [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
Insert Sort

? The insert sort has two loops, and the outer loop moves the elements of the array one by one, while the inner loop compares the elements selected in the outer loop and the elements behind it. If the selected element is small in the outer loop, the array element moves to the right, freeing up the element in the inner loop. each step inserts a record to be sorted by the size of its key value into the appropriate position in the previously sorted file until all is Inserted.

description of the direct insertion sorting algorithm < There are 1-9 cards marked with a number:
1. Take the first card and put it directly to the left of the Table.
2. Take out the second card, if the number of the card is less than the first one, move the first card to the right, or put it on the right;
3. Take out the nth card and the card with section n-1, N-2 The 1th contrast, less than or equal to the right shift, continues to contrast, which is greater than the stop contrast to insert the value into the corresponding Position.

 function insertionsort(dataary) {    vartemp, inner;//outer Loop (skips The first value, because the first one is placed directly to the far left)     for(varOuter =1, Len = dataary.length; Outer < len;        Outer++) {temp = dataary[outer]; Inner = outer;//inner loop, Less than the left value of the move to give way         while(inner >0&& (dataary[inner-1] (>= temp)) {dataary[inner] = dataary[inner-1];        inner--;    } dataary[inner] = temp; }returndataary}//testConsole.log (insertionsort (dataary));//[1, 2, 3, 4, 5, 6, 7, 8, 9]
Hill sort

? The algorithm is improved on the basis of inserting sort. It requires a pre (or Dynamic) definition of an interval sequence to represent the interval between elements that are compared during the sorting process. The direct insertion sorting algorithm is used to sort each set of elements that are spaced, and as the number of interval sequences decreases, each group contains more and more elements, and when the interval is reduced to 1 o'clock, the entire file is divided into a group, and the algorithm Terminates. This ensures that most of the elements are in the correct position at the beginning of the last processing, and that multiple data exchanges must be performed, which is where the hill sort is more efficient than the insert Sort.

description of the hill sort algorithm:
1. First take an integer less than n D1 as the first interval, grouping all the records in the File. All records with a multiple of D1 are placed in the same group. first, the direct insertion in each group is sorted;
2. d2<d1 Repeat the above grouping and sorting by taking the second interval value;
3. Until the interval is 1, all records are placed in the same group for direct insert Sorting.

/** * Hill sort * @param dataary data array * @param gaps interval Array * * function shellsort(dataary, gaps) {    vartemp, inner, currentgap;//traversal interval     for(varg =0, GLen = gaps.length; G < gLen; G++) {//current intervalCurrentgap = gaps[g];//direct insertion of extra-normal loop         for(varOuter = currentgap, Len = dataary.length; Outer < len;           Outer++) {temp = dataary[outer]; Inner = outer;//direct Insert In-loop (note The contrast interval Value)            while(inner >= currentgap && (dataary[inner-currentgap] >= temp))               {dataary[inner] = dataary[inner-currentgap];           Inner = inner-currentgap;        } dataary[inner] = temp; }    }returndataary;}//testConsole.log (shellsort (dataary, [3,2,1]));//[1, 2, 3, 4, 5, 6, 7, 8, 9]
Merge sort

Combine a series of ordered subsequence sequences into a large complete ordered SEQUENCE. Merge sort is usually implemented using recursive returns.

Top-down Merge Sort (recursive)

 function mergesort(dataary) {    if(dataary.length = = =1) {returndataary; }varMID =Math. Floor (dataary.length/2);varLeftary = Dataary.slice (0, mid);varRightary = Dataary.slice (mid);returnMerge (mergesort (leftary), mergesort (rightary));}/** * Merge array * @param dataary */ function merge(leftary, Rightary) {    varresult = []; while(leftary.length >0&& rightary.length >0) {if(leftary[0] < rightary[0]) {result.push (leftary.shift ()); }Else{result.push (rightary.shift ()); }    }returnResult.concat (leftary). concat (rightary);}//testConsole.log (mergesort (dataary));//[1, 2, 3, 4, 5, 6, 7, 8, 9]

? The above mergesort () is executed 2n-1 times (the above is executed 17 times), once the number of array elements increased, the use of recursive way will no longer be desirable, the number of elements more than 1500 in the Firfox will cause stack overflow!

bottom-up Merge Sort (iteration)

? The dataset is first decomposed into an array of only one element, and then merged by creating a set of left and right arrays, each merging ensures that the data is sequenced until all the data is sorted at the End.

 function mergesort(dataary) {    if(dataary.length <2) {returndataary; }varStep =1;//control sub-sequence Size    varleft, right;//left and right subscript     while(step < Dataary.length) {left =0; right = step; while(right + Step) <= Dataary.length)            {mergearrays (dataary, left, left+step, right, right+step);            left = right + step;        right = left + step; }//elements that cannot be grouped        if(right < Dataary.length)        {mergearrays (dataary, left, left+step, right, dataary.length); } Step = Step *2; }returndataary;}/** * Merge Array < contains header, not including tail > * @param ary * @param startleft * @param endleft * @param startright * @param endright */< /c6> function mergearrays(ary, startleft, endleft, startright, endright) {    varLeftary =New Array(endleft-startleft +1), rightary =New Array(endright-startright +1);varK = startleft; for(vari =0; I < (leftary.length-1);        I++) {leftary[i] = ary[k];    k++; } leftary[leftary.length-1] =Infinity;//sentinel ValueK = startright; for(varj =0; J < (rightary.length-1);        J + +) {rightary[j] = ary[k];    k++; } rightary[rightary.length-1] =Infinity;//sentinel Value    //compare left and right element size    varm =0, n =0; for(varK = startleft; K < endright; K++) {if(leftary[m] <= Rightary[n])            {ary[k] = leftary[m];        m++; }Else{ary[k] = rightary[n];        n++; }    }}//testConsole.log (quickSort (dataary));//[1, 2, 3, 4, 5, 6, 7, 8, 9]
Quick Sort

? Fast sorting is one of the fastest sorting algorithms for working with large data sets. Its core idea is "divide and conquer". Set the base value to decompose the data once into different sub-sequences containing smaller and larger elements in a recursive manner, and then repeat until all the data becomes orderly.

Quick Sort Algorithm description:
1. Select a datum element and separate the list into two sub-sequences;
2. Place all data that is less than the datum element to the left of the Datum value, and the data greater than the datum element is placed to the right of the Datum value;
3. Repeat steps 1 and 2 for the sub-sequences of the smaller elements and the subsequence of the larger elements, respectively.

Quick Sort < way;: starting from the left loop array vs. base value

function  Span class= "hljs-title" >quicksort   (dataary)  { if  (dataary.length = = = 0 ) {return  []; } var  left = [], right = []; var  pivot = dataary[0 ]; for  (var  i = 1 ; i < dataary.length; i++) {dataary[i] < pivot Left.push (dataary[i]): Right.push (dataary[i]); } return  quickSort (left). concat (pivot, quickSort (right));} //test  console.log (quickSort (dataary)); //[1, 2, 3, 4, 5, 6, 7, 8, 9]  

Quick Sort < two;: moves from the left and right sides, compared to the base value

 function quickSort(arr, left, right) {    if(left > Right)return;vartemp, i = left, j = right;//set Reference Value    varPivot = arr[left]; while(i! = J) {//start from the right (find the first data less than the base Value)         while(i < J && arr[j] >= Pivot)        {j--; }//then start from the left (find the first data larger than the base Value)         while(i < J && arr[i] <= Pivot)        {i++; }//exchange data above two elements, continue to find, until I and J meet        if(i < J)            {temp = arr[i];            arr[i] = arr[j];        arr[j] = temp; }    }//exchange the base value with the meeting data < Ensure that the base value is located in the central position of the element >temp = arr[i];    arr[i] = arr[left]; arr[left] = temp;the left array of the//base values are executed recursively as described aboveQuickSort (arr, left, i-1);//the Right array of the base value is executed recursively as described aboveQuickSort (arr, i +1, right);returnarr;}//testConsole.log (quickSort (dataary,0, dataary.length-1));//[1, 2, 3, 4, 5, 6, 7, 8, 9]
Summarize

Bubble sort, Select sort, Insert sort as basic sorting Algorithm , Hill sort, merge sort (iteration), Quick sort to advanced sort algorithm :

Sorting Algorithms 100 Elapsed Time 10,000 Elapsed Time 100,000 Elapsed Time
Bubble sort 16 ms 584 ms 54619 ms
Select sort <1 ms 183 ms 18175 ms
Insert Sort <1 ms 27 ms 2660 ms
Hill sort <1 ms 13 ms 1384 MS
Merge sort (iteration) <1 ms 6 ms 40 ms
Quick Sort (way One) <1 ms 17 ms 98 MS
Quick Sort (way Two) <1 ms 3 ms 13 ms

JavaScript algorithm-sorting algorithm

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.