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
static void Bubble_sort (int[] unsorted) {for (int i = 0; i < unsorted. Length; i++) {for (int j = i; J < unsorted. Length; J + +) { if (Unsorted[i] > Unsorted[j]) { int temp = unsorted[i]; Unsorted[i] = unsorted[j]; UNSORTED[J] = temp; }}}} static void Main (string[] args) { int[] x = {6, 2, 4, 1, 5, 9}; Bubble_sort (x); foreach (var item in x) { Console.WriteLine (item); } Console.ReadLine (); }
Bubble Sort Bubble sort