A preliminary study of JS sort algorithm (i) __ algorithm

Source: Internet
Author: User

Preface Sort Realization Bubble Sort Select sort Insert sort merge sorting quick sort sorting efficiency conclusion

Preface

Here are some JavaScript version of the sorting algorithm, reference to the following article: JavaScript data structure and algorithm (iv), sharing a sort of visual page: the implementation of the various sorting algorithm by HTML5 animation comparison sort

Define an exchange function first:

function swap (arr, idx1, idx2) {//value of two indexes for interactive arrays
  const AUX = arr[idx2]
  arr[idx2] = arr[idx1]
  arr[idx1] = aux< c5/>}

In fact, there are several ways of exchanging value, such as:

If the value is a simple numeric type let
a = 1, b = 2
a =^ b
b =^ a
=^ b
//array exchange of the Sao operation, the readability is poor let
a = ' AA ', B = ' BBB ' 
  a = [B, b = a][0]
//You can also use ES2015 's deconstruction syntax let
a = ' QW ', b = ' er '
[a, b] = [B, a]
//If the value of the array member is exchanged
l ET arr = [1, 2]
[arr[0], arr[1]] = [arr[1], arr[0]]
//The method of exchanging the most intuitive temporary variables here
Bubble Sort

Description: Bubble sort compares any two adjacent items and exchanges them if the first one is larger than the second. Element items move up in the correct order, just as bubbles rise to the surface, so the bubble sort gets its name.
Algorithm implementation:

function Bubblesort (arr) {
  const LEN = arr.length for
  (Let i = 0;i < len-1;i++) {//The first row is the last one in the array, and then the second, and the The first bit of the array is sorted after the second bit, so the outermost for loop is len-1
    (Let j = 0;j < len-1-i;j++) {
      if (Arr[j] > arr[j + 1]) {
  swap (Arr, J, j + 1)
      }} return
  arr
}
Select Sort

Description: The idea of choosing a sort is to find the smallest value in the data structure and place it in the first place, then find the second small value and place it in the second place, and so on.
Algorithm implementation:

function Selectionsort (arr) {//select sort
  Const LEN = arr.length let
  minidx for
  (var i = 0;i < len;i++) {
  MINIDX = I//initialization minimum index for
    (var j = i + 1;j < len;j++) {
      if (ARR[J) < ARR[MINIDX]) Minidx = j//Update min The index of the value
    }
    if (Minidx!== i) {
      swap (arr, I, MINIDX)/exchange value
    }
  } return
  arr
}
Insert Sort

Description: The basic idea of inserting a sort is to insert a record to be sorted each step into the appropriate position in the previously sorted file by the size of its key value until all the inserts are complete. This algorithm is similar to the selection sort, which is to find the nth value in an unordered array, and then exchange the values of the nth members of the arrays. The insert sort is the first element of an unordered array, and then the members of the sorted array are compared to the reverse, if the value of the member of the ordered array is greater than the element to be sorted, the value is assigned to the next ordered array member. Until you find an array member that is smaller than the element you want to sort, and then insert it behind the small element.
Algorithm implementation:

function Insertionsort (arr) {//Insert sort
    Const LEN = arr.length Let
    temp, J for
    (Let i = 1;i < len;i++) {
        temp = Arr[i]
        j = i while
        (J > 0 && arr[j-1] > Temp) {
            arr[j] = arr[j-1]
            j--
        }
        ar R[J] = temp
    } return
    arr
}
Merge Sort

Description: 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 two-way merge.
Algorithm implementation:

function MergeSort (arr) {//merge sort
    function Mergesortrec (array) {
        Const LEN = array.length
        if (len = = 1) retur N array
        Const MID = Math.floor (LEN/2)
        const LEFTARR = Array.slice (0, mid)
        const RIGHTARR = Array.slice (Mid, Len) return
        merge (Mergesortrec (Leftarr), Mergesortrec (Rightarr))
    }
    function Merge (Leftarr, Rightarr) {
        const RESULT = [] let
        il = 0, ir = 0 while
        (Il < leftarr.length && ir < rightarr.length) {
  if (Leftarr[il] < Rightarr[ir]) {
                result.push (leftarr[il++])
            } else {
                Result.push (rightarr[ir++) }
        } while
        (Il < leftarr.length) {
            result.push (leftarr[il++])
        } while
        (IR < Rightarr.length) {
            result.push (rightarr[ir++])} Return to result
        } return
    Mergesortrec (arr )
}
Quick Sort

Description: A trip to sort the data to be sorted into two separate parts, where all of the data is smaller than all the data in the other part, and then the two parts of the data are sorted quickly by this method
Algorithm implementation:

function QuickSort (arr) {//Quick sort
    Const LEN = arr.length
    if (Len <= 1) return arr
    const PIVOTIDX = Math.flo  or (LEN/2)
    const PIVOT = arr.splice (pivotidx, 1) [0] Let
    leftarr = [], Rightarr = [] for
    (Let i = 0;i < len -1;i++) {
        if (Arr[i] < pivot) {
            Leftarr.push (Arr[i])
        } else {
            Rightarr.push (Arr[i])
        }
    }< C12/>return QuickSort (Leftarr). Concat ([pivot], QuickSort (Rightarr))
}
Sorting Efficiency

First, create an array method that generates random data:

Const COUNT = 1000//number of array members to be generated
const TESTARR = Array (count). Fill (). map (Val => ~ ~ (math.random () * COUNT))

The results are as follows:

-
sort algorithm \ Number of sorted arrays 1000 10000 100000
Bubble sort 0.560ms 5.866ms 252.304ms 24602.321ms
Select sort 0.209ms 3.143ms 119.986ms 15131.266ms
Merge sort 0.280ms 2.847ms 9.750ms 68.401ms
Quick Sort 0.190ms 1.800ms 8.213ms 58.990ms

From the above results can be seen intuitively, four sorting algorithms in the fastest sorting performance, within 100 of the array element, everyone's performance is almost, 1ms, 1000 elements of the array has been opened the gap, but fortunately, the human response speed of the shortest poem 100ms, so can also accept. But at 100000 data element level, bubble sort need 24s, choose to sort also 15s, time is longer, and merge sort and quick sort performance is also outstanding, less than 70ms.
In fact, under test, merge sort and quick sort can keep the amount of data under processing millions in seconds. Conclusions

A good sorting algorithm is very effective to improve the efficiency of large scale data processing.

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.