Get the App
SLTechnology News&Howtos  ›  Development  › 

How to realize Bubble sorting in javascript

Shulou Source: shulou.com Published: 2022-06-02 13:15:43 10月01日 Update

This article is about how to implement bubble sorting in javascript. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

What is Bubble sorting

Bubble sort, Bubble Sort, by comparing the size of two adjacent elements in turn, in each comparison process, the two elements are exchanged to achieve the purpose of order.

If a set of unordered sequences wants to be sorted from small to large, then the comparison of the two elements is achieved by exchange, and the element on the left is smaller than the element on the right.

If an unordered sequence wants to sort from large to small, then the comparison of the two elements is achieved by swapping, and the element on the left is larger than the element on the right.

Like a bubble in a carbonated drink, it bubbles from the bottom to the top.

Second, give an example

If there are 2, 4, 7, 5, 5, 3, 6, 1, this group of numbers

First round:

ITunes 0

J (inner loop) cycle 6 times, the work done by the inner loop: comparing the two adjacent numbers, the large one will eventually be placed in the back, the small one in front, the outer loop control times in one cycle, and the inner loop to judge.

Jennifer 0 1 2 3 4 5

2 2 2

4 4 4

7 7 7 5 5 5

5 5 5 7 3 3 3

3 3 3 7 6 6

6 6 6 7 1

1 1 1 7

Arr [0] arr [1] arr [2]

Arr [1] arr [2] arr [3]

Second round:

ITunes 1

J (inner loop) cycle 5 times

Jennifer 0 1 2 3 4 5

2 2 2

4 4 4

5 5 5 3 3 3

3 3 3 5 5 5

6 6 6 1

1 1 1 6

7 7 7

Arr [0] arr [1] arr [2]

Arr [1] arr [2] arr [3]

Round 3:

ITunes 2

J (inner loop) 4 cycles

2 2 2

4 4 3 3 3

3 3 4 4 4

5 5 5 1

1 1 1 5

6 6 6

7 7 7

Round 4:

ITunes 3

J (inner loop) cycle 3 times

2 2 2

3 3 3

4 4 4 1

1 1 1 4

5 5 5

6 6 6

7 7 7

Round 5:

ITunes 4

2 2 2

3 3 1

1 1 3

4 4 4

5 5 5

6 6 6

7 7 7

Round 6:

ITunes 5

2 1

1 2

3 3

4 4

5 5

6 6

7 7

, /

/ / example 1:function show () {var arr= [2 for 4, 7, 5, 3, 6, 1]; for (var item0, witi)

Tags: Loop element sort inner layer two content right series more examples article good practical orderly from small to big three rounds small example four rounds outer layer Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Microsoft Shulou Information Xiaomi Shulou Tech Info MySQL