Summary of JS sorting algorithm

亚连
Release: 2018-06-21 11:02:07
Original
1326 people have browsed it

This article mainly introduces the bubble sort, selection sort and insertion sort of the JS sorting algorithm. It analyzes the concepts, principles and implementation methods of bubble sort, selection sort and insertion sort in the form of examples. Friends in need can refer to it. Next

The examples in this article describe the JS sorting algorithms of bubble sort, selection sort and insertion sort. Share it with everyone for your reference. The details are as follows:

Bubble sort:

Compare the data in the array in sequence between two adjacent ones. The size of the number.

If the previous data is greater than the later data, exchange the two numbers.

Time complexityO(n^2)

function bubble(array){ var temp; for(var i=0; iarr[j+1]){ temp = arr[j+1]; arr[j+1] =arr[j]; arr[j]=temp; } }console.log(arr); } }//冒泡排序
Copy after login

Selection sort:

First Select the smallest data from the original array and exchange it with the data at position 1.

Then select the next smallest data from the remaining n-1 data and exchange it with the data at the second position.

Repeat until the last two data are exchanged.

Time complexityO(n^2)

function selectionSort(array){ var min,temp; for(var i=0; i
        
Copy after login

Insertion sort:

First Compare the first two data from small to large.

Then compare the third data with the first two arranged data, and insert the third data into the appropriate position. And so on.

(Insertion sort has two loops. The outer loop moves the arrays one by one, and the inner loop compares the element selected by the outer loop with the number in front of it.)

Time complexityO(n^2)

function insertSort(arr){ var temp, j; for(var i=1; i0 && arr[j-1]>temp){ arr[j]=arr[j-1]; j--; } arr[j]=temp; } }
Copy after login

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

The process of encapsulating and submitting data in a form

Recording the occurrence of repeated elements in JavaScript Times

How to implement multiple AJAX requests using JQUERY

How to call vuex to store interface data in vue.js

The above is the detailed content of Summary of JS sorting algorithm. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!