This article brings to you the content is about the Java sorting algorithm: Bubble sorting algorithm Implementation (code), there is a certain reference value, the need for friends can refer to, I hope you have some help.
Bubble Sort method is one of the most basic sorting methods, and the mechanism of bubble sorting is a simple sort method which is implemented by iterating through elements and adjusting the order of neighboring elements. The essence of the bubbling sort is the comparison of the adjacent two elements, and then the position is swapped in ascending or descending order.
Below is the code for descending bubble sort:
public class Training {public static void main (string[] args) { int [] array = {3,2,5,1,4};for (int time = 1; looptime < Array.Length; looptime++) {for (int i = 0,temp = 0; i < array.length-looptime; i++) {if (Array[i+1]>array[i]) {temp = Array[i+1];a RRAY[I+1] = array[i];array[i] = temp;}}} for (int i = 0; i < Array.Length; i++) {System.out.println (array[i]);}}}
the for The loop will place large data in the appropriate position once per cycle, such as Looptime =1 to put the maximum data in the last ; Looptime =2 ; Place the second largest data in the second-to-last element position; Array.length-looptime : from the aspect of improving the performance of the code, the number of cycles of "redundant" loops is reduced.
The following is the result of the operation:
Of course, there is an ascending sort of bubble, in fact, only the "if (Array[i+1]>array[i])" In the Boolean condition is changed to array[i+1]<array[i] can.
for (int i = 0; i < array.length-time; i++) {if (Array[i+1]<array[i]) {temp = a RRAY[I+1];ARRAY[I+1] = array[i];array[i] = temp;}}