Bubble Sort Idea:
The small always take the big forward and always take the back. Steps:
1. Compare adjacent elements, if the first one is larger than the second, just swap him for two. 2. In this way to the No. 0 data to the first N-1 data traversal, the largest data sank to the N-1 position 3.n=n-1, if N is not 0 to repeat the previous two steps, or sorting completed. Let's take a look at the results of the operation:
For example, array {3,2,10,5,7,2,4,6}; Adjacent two elements compare size and then swap order if the previous one is greater than the latter. The steps we use to bubble it are as follows:
The first trip came down: i=0; J=0 is less than arr.length-1-i (note: The next two elements of the black body in the Order of Exchange) (j=0)--> 2, 3, 5, 7, 2, 4, 6 (j=1)--> 2, 3, 5, 7, 2, 4- -> 2, 3, 5, 7, 2, 4, 6 (j=3)--> 2, 3, 5, 7, 2, 4, 6 (j=4)--> 2, 3, 5, 7, 2, 4, 6 (j=5)--> 2, 3, 5, 7, 2, 4, ten, 6 (j=6)--> 2, 3, 5, 7, 2, 4, 6, 10 The first trip bubbling down was the result, and the biggest 10 came out.
The second trip came down: i=1; J=0 J is less than arr.length-1-i; (j=0)--> 2, 3, 5, 7, 2, 4, 6, (j=1)--> 2, 3, 5, 7, 2, 4, 6, (j=2)--> 2, 3, 5, 7, 2, 4, 6, (j=3) ; 2, 3, 5, 2, 7, 4, 6, (j=4)--> 2, 3, 5, 2, 4, 7, 6, (j=5)--> 2, 3, 5, 2, 4, 6, 7, 10, two. The trip bubbling down is the result of the biggest 7.
By analogy until I run to the previous position of N-1, the end. This allows the array to be sorted and the specific code operation is as follows:
public class Maopao {public
static void Main (string[] args) {
//TODO automatically generated method stub
int[] arr = {3,2,10,5,7,2,4,6 };
Maopaopaixu (arr);
for (int i = 0; i < arr.length i++) {
System.out.print (arr[i]+ "\ t");
}
public static void Maopaopaixu (int[] arr) {for
(int i = 0; i < arr.length-1; i++) {
int temp = 0;
for (int j = 0; J < Arr.length-1-i; J +) {
if (Arr[j] > Arr[j+1]) {
temp = arr[j];
ARR[J] = arr[j+1];
ARR[J+1] = temp;}}}
But the efficiency is not very high, we will be in the first for the loop to print out the exchange of the array to find in the next figure red Line position he has been ordered, repeated it several times so we need to do some optimization, when the bubble, when its elements are not the biggest out of the time we can think that is already ordered, You can stop the traversal. :
The optimized code is as follows:
public static void Maopaopaixu (int[] arr) {for
(int i = 0; i < arr.length-1; i++) {
int temp = 0;
Boolean tag = false;
for (int j = 0; J < Arr.length-1-i; J +) {
if (Arr[j] > Arr[j+1]) {
temp = arr[j];
ARR[J] = arr[j+1];
ARR[J+1] = temp;
Tag = true;
}
if (!tag) {break;}}}
When we look at the cycle again, the number of times has been significantly reduced
The bubble ended like this ....