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); } }//冒泡排序
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; } }
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!