This article talks aboutbubble sortinginJavaScript. If you don’t know about bubble sorting in JavaScript, then let’s take a look at this article. Bubble sorting is simply implemented using JavaScript. Okay, let’s stop talking and get to the point!
Bubble sort
As one of the simplest sorting algorithms, bubble sort gives me the feeling of Abandon It feels the same as it appears in the word book. It is always on the first page, so it is the most familiar. . . There is another optimization algorithm for bubble sorting, which is to set a flag. When the elements are not exchanged during a sequence traversal, it proves that the sequence is in order. But this improvement doesn't do much to improve performance. . .
When is the fastest time?
When the input data is already in positive sequence (it is already in positive sequence), what is the use of bubble sorting? . . )
When is the slowest time?
When the input data is in reverse order (Write afor loopWon’t it work to output the data in reverse order? Okay, why should I use bubble sorting? I’m free.)
Bubble sorting animation
##JavaScript code accomplish:function bubbleSort(arr) { var len = arr.length; for (var i = 0; i < len; i++) { for (var j = 0; j < len - 1 - i; j++) { if (arr[j] > arr[j+1]) { //相邻元素两两对比 var temp = arr[j+1]; //元素交换 arr[j+1] = arr[j]; arr[j] = temp; } } } return arr;}
The above is all the content of this article. If you don’t know much about it, you can easily master it by implementing more of both sides!
Related recommendations:
Js bubble sort and quick sort detailed explanation
The above is the detailed content of Detailed explanation of bubble sort in JavaScript. For more information, please follow other related articles on the PHP Chinese website!