What is a bubble sort: from start to finish comparing the size of two adjacent numbers, if they meet the conditions then compare
[Note]: from small to large sort
suppose you have an array var arr = [9,8,7,6, 5,4]; we want to sort this array in accordance with the rules then bubble sort of evolution and we can try
first comparison
9 7 6 5 4 8
8 7 6 5 4 9
8 7 6 5 4 9
8 7 4 9 5 6
8 7 6 5 4 9
8 7 6 5 4 9
by comparing the first round, we will compare the greatest number 9 out, but this is not the end result we wanted, so we also need to continue to compare
the first secondary comparison
8 7 6 5 4
7 6 5 4 8
7 6 5 4 8
7 6 5 4 8
7 6 5 4 8
we compare the maximum number eight out of the second round by comparing
third comparison
7 6 5 4
6 4 5 7
6 5 4 7
6 5 4 7
we compare the maximum number seven out by comparing the
fourth Compare
6 5 4
5 6 4
5 4 6
by comparison we will compare the highest number 6 out of
the fifth comparative
4 5
4 5
By comparison we will compare the array 5 out
[Note: The above evolution we come to a conclusion that is comparable number equal to the array length minus one; comparing the number of pairwise comparisons of every internal needs -1-i of the array length
* /
var TEMP;
for (var I = 0; I <-arr.length. 1; I ++) {
for (var 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;
}
}
}
/ *
What is the selection sort
similar to Health Warning, like, who won the first one who will stand
Suppose an array var arr = [9,8,7,6,5]; we want to sort this array in accordance with the rules then we can choose to sort of evolve and try
The first round of comparison
987. 5. 6
. 8. 5. 6. 7. 9
. 7. 9. 5. 6. 8
. 6 987. 5
. 5 987. 6
a first round of comparison the smallest number in the first place
the second round of comparator
987 . 6
. 8. 9. 7. 6
. 7. 8. 9. 6
. 6. 8. 9. 7
a second round of comparison the smallest number in the first place
the third round of comparison
. 9. 8. 7
. 8. 9. 7
. 7. 9. 8
the third round of the smallest number in comparison a first
fourth round of comparison
. 9. 8
. 8. 9
the fourth round of comparison is completed
[summary]: first, look at the number of comparisons rule: length of the array -1, round comparison rule: each position of comparison is the current number +1 for the comparison position
* /
var TEMP;
for (var I = 0; I <-arr.length. 1; I ++) {
for (var = I + J. 1; J <arr.length; J ++) {
IF (ARR [I]> ARR [J]) {
TEMP = ARR [I];
ARR [I] = ARR [J];
ARR [J] = TEMP;
}
}
}