Classic Sort algorithm-bubble sort bubble sort
The principle is that the adjacent number 22 is compared, in order from small to large or from large to small to exchange,
After such a trip, the largest or smallest number was exchanged to the last,
And then start from the beginning to the 22 comparison exchange, until the end of the second-to-last, the rest looks like examples
Examples for small to large sort,
Original array to sort | 6 | 2 | 4 | 1 | 5 | 9 |
First trip sort (outer loop)
First 22 comparison 6 > 2 swap (inner loop)
Pre-swap status | 6 | 2 | 4 | 1 | 5 | 9 |
Post-swap status | 2 | 6 | 4 | 1 | 5 | 9 |
Second 22 comparison, 6 > 4 swap
Pre-swap Status | 2 | 6 | 4 | 1 | 5 | 9 |
Post-swap Status | 2 | 4 | 6 | 1 | 5 | 9 |
Third 22 comparison, 6 > 1 swap
Pre-swap Status | 2 | 4 | 6 | 1 | 5 | 9 |
Post-swap Status | 2 | 4 | 1 | 6 | 5 | 9 |
Fourth time 22 comparison, 6 > 5 swap
Pre-swap Status | 2 | 4 | 1 | 6 | 5 | 9 |
Post-swap Status | 2 | 4 | 1 | 5 | 6 | 9 |
Fifth time 22 comparison, 6 < 9 no swap
Pre-swap Status | 2 | 4 | 1 | 5 | 6 | 9 |
Post-swap Status | 2 | 4 | 1 | 5 | 6 | 9 |
Second trip sort (outer loop)
First 22 comparison 2 < 4 no swap
Pre-swap status | 2 | 4 | 1 | 5 | 6 | 9 |
Post-swap status | 2 | 4 | 1 | 5 | 6 | 9 |
Second 22 comparison, 4 > 1 swap
Pre-swap Status | 2 | 4 | 1 | 5 | 6 | 9 |
Post-swap Status | 2 | 1 | 4 | 5 | 6 | 9 |
Third 22 Comparisons, 4 < 5 non-exchangeable
Pre-swap Status | 2 | 1 | 4 | 5 | 6 | 9 |
Post-swap Status | 2 | 1 | 4 | 5 | 6 | 9 |
Fourth time 22 comparison, 5 < 6 no swap
Pre-swap Status | 2 | 1 | 4 | 5 | 6 | 9 |
Post-swap Status | 2 | 1 | 4 | 5 | 6 | 9 |
Third trip sort (outer loop)
First time 22 comparison 2 > 1 swap
Post-swap status | 2 | 1 | 4 | 5 | 6 | 9 |
Post-swap status | 1 | 2 | 4 | 5 | 6 | 9 |
Second 22 comparison, 2 < 4 non-exchangeable
Post-swap Status | 1 | 2 | 4 | 5 | 6 | 9 |
Post-swap Status | 1 | 2 | 4 | 5 | 6 | 9 |
Third 22 Comparisons, 4 < 5 non-exchangeable
Post-swap Status | 1 | 2 | 4 | 5 | 6 | 9 |
Post-swap Status | 1 | 2 | 4 | 5 | 6 | 9 |
Four-trip sort (outer loop) No swap
Five-trip sort (outer loop) No swap
Sort finished, output final result 1 2 4 5 6 9
Code for reference only
Static voidBubble_sort (int[] unsorted) { for(inti =0; I < unsorted. Length; i++) { for(intj = i; J < unsorted. Length; J + +) { if(Unsorted[i] >Unsorted[j]) { inttemp =Unsorted[i]; Unsorted[i]=Unsorted[j]; UNSORTED[J]=temp; } } } } Static voidMain (string[] args) { int[] x = {6,2,4,1,5,9 }; Bubble_sort (x); foreach(varIteminchx) {Console.WriteLine (item); } console.readline (); }
Bubble Sort Animation Demo
Classic Sort algorithm-bubble sort bubble sort