JS Bubble Sort Selection Sort and Insertion Sort Example Analysis

小云云
Release: 2017-12-14 09:25:12
Original
2091 people have browsed it

This article mainly introduces the bubble sort, selection sort and insertion sort of 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 who need it can refer to it. I hope Can help everyone.

Bubble sorting:

Compare the sizes of two adjacent numbers in order for the data in the array.

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

Related recommendations:

Counting sorting and cardinality implemented by JS Sorting algorithm example_javascript skills

Detailed explanation of sorting algorithm

Detailed explanation of javascript array deduplication and quick sort algorithm examples

The above is the detailed content of JS Bubble Sort Selection Sort and Insertion Sort Example Analysis. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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!