Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to realize Bubble sorting in C #

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

This article mainly shows you "how C#realizes bubble sorting", the content is simple and easy to understand, and the organization is clear. I hope it can help you solve your doubts. Let Xiaobian lead you to study and learn this article "how C#realizes bubble sorting".

1. Simple description of algorithm idea

Bubble sort to traverse each of the data to be arranged, and pairwise comparison, if the order is not on its transposition, until the sort is complete. First pass: compare the first and second numbers, putting the decimal first and the large number last. Then compare the 2nd number with the 3rd number, putting the decimal first and the large number last, and so on until you compare the last two numbers, putting the decimal first and the large number last. Repeat the first step until all sorting is complete.

Imagine the smallest data element slowly "floating" from the bottom to the top like a bubble.

2. Simple demonstration of algorithm

Example: To sort array matrix: int[] arr={8,6,9,2};

First sorting:

1st sort: 8 vs 6, 8 is greater than 6, swap positions: 6 8 9 2

2nd sorting: 8 and 9 compare, 8 less than 9, do not change position: 8 6 9 2

3rd sort: 9 and 2 compare, 2 less than 9, swap positions: 8 6 2 9

The first pass was compared 3 times in total, ranking result: 8 6 2 9

---------------------------------------------------------------------

Second sorting:

1st sorting: 8 and 6 compare, 8 is greater than 6, exchange position: 6 8 2 9

2nd sort: 8 vs 2, 8 is greater than 2, swap positions: 6 2 8 9

The second round was compared 2 times, ranking result: 6 2 8 9

---------------------------------------------------------------------

Third sorting:

1st sorting: 6 and 2 compare, 6 is greater than 2, exchange position: 2 6 8 9

The third pass has 1 comparison in total, ranking result: 2 6 8 9

---------------------------------------------------------------------

Final Results: 2 6 8 9

---------------------------------------------------------------------

It can be seen from this: N numbers to be sorted, a total of N-1 sorting, each i sorting times is (N-i) times, so you can use double loop statements, the outer layer controls the number of loops, the inner layer controls the number of loops per loop:

for(int i=0;i

Tags: Sort position result Category number element content Big number Decimal algorithm Article Loop Code data number Learning help Control No minimum Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Technology Docker Huawei vpn NVidia