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
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 (); }
A lot of interviews have been asked for this problem. Either a written test or a machine test. So let's take a good look at it.
Java Bubble Sort