Detailed explanation of bubble sort in JavaScript

韦小宝
Release: 2018-03-14 13:54:57
Original
2467 people have browsed it

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

Detailed explanation of bubble sort in JavaScript

##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;}
Copy after login

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!

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!