First, the principle of the algorithm.
The Bubble sorting algorithm works as follows:
- Compares the adjacent elements. If the first one is bigger than the second one, swap them both.
- Do the same work for each pair of adjacent elements, starting with the last pair from the first pair to the end. At this point, the last element should be the maximum number.
- Repeat the above steps for all elements, except for the last one.
- Repeat the above steps each time for less and fewer elements until there are no pairs of numbers to compare
Second, the code implementation.
public static void Bubblesort () {
Int[] arr = {8,3,4,2,6,3,10,13,15,38};
for (int i=0; i< arr.length; i++) {
for (int j = 0; j< arr.length-i-1; j + +) {
if (Int[j] < int[j+1]) {
int temp = int[j+1];
INT[J+1] = Int[j];
INT[J] = temp;
}
}
}
}
Third, the complexity of the algorithm.
Time complexity if the initial state of the file is a positive sequence, a scan can be done in order. The required number of keyword comparisons and record moves has reached the minimum value:. So, the best time to bubble sort is complexity.
If the initial file is reversed, a sequencing is required. The Sub-keyword comparison (1≤i≤n-1) is performed for each order, and each comparison must move the record three times to reach the Exchange record location. In this case, the comparison and the number of moves reach the maximum: The worst time complexity for the bubbling sort is. Overall, the average time complexity for the bubble sort is. Iv. stability of the algorithm. The bubble sort is to move the small element forward or the large element back. The comparison is an adjacent two element comparison, and the interchange also occurs between these two elements. Therefore, if the two elements are equal, they will not be exchanged, and if the two equal elements are not adjacent, then even if the two are adjacent by the preceding 22 interchanges, this time it will not be exchanged, so the order of the same elements is not changed, so the bubble sort is a stable sort algorithm.
Java Bubble sort