Principle: Assigning large values of adjacent elements to the right
Idea: ①1. Compares the first element in the collection or array to the second element and assigns a larger value to the right;
2. Compare the second element to the third one, and the larger value to the right;
.......
(N-1). Compares the N-1 element with the nth element and assigns a larger value to the right;
From this, the maximum value of the element in the set is obtained and assigned to the element n;
② Repeat Operation ① get the new value of the element N-1, and get the new value of the element N-2;
......
Get the value of element 2 and get the value of element 1
Instance:
Sort for arr[5] = {3,5,2,8,1}:
First trip Sort:
3,5,2,8,1;
3,2,5,8,1;
3,2,5,8,1;
3,2,5,1,8;
Second trip sort:
2,3,5,1,8;
2,3,5,1,8;
2,3,1,5,8;
Third trip Sort:
2,3,1,5,8;
2,1,3,5,8;
Sequence Four:
1,2,3,5,8;
This shows: N numbers to sort complete, a total of N-1 sequencing, every I trip to the order of (n-i) times, so you can use the double loop statement, the outer control loop how many times, the inner layer control each trip cycle times, namely:
for (i = 0; i<arr.length-1;i++) {//outer control how many trips to sort
for (j = 0; j<arr.length-1-i;j++) {//The inner layer controls how many times the adjacent element size is judged by the order of each trip
if (Arr[j]>arr[j+1]) {
temp = Arr[j];
ARR[J] = arr[j+1];
ARR[J+1] = temp;
}
}
}
Classic algorithm-bubble sort (Java)