New school Bubble sorting, New School Bubble Sorting
Import java. util. collections;
Public class MaoPaoPaiXu {
Public static void main (String [] args ){
Scanner input = new Scanner (System. in); // create a Scanner
System. out. print ("array length :");
Int num = input. nextInt (); // enter the array length on the keyboard.
Int [] nums = new int [num]; // defines an array
Int I, j; // defines two cyclic Variables
Int temp; // Temporary Variable
For (int k = 0; k <nums. length; k ++ ){
System. out. print ("th" + (k + 1) + "number :");
Nums [k] = input. nextInt ();
}
System. out. print ("Before sorting :");
For (int k = 0; k <nums. length; k ++ ){
System. out. print (nums [k] + "");
}
/**
* Bubble Sorting (Dual Loop)
*/
For (int k = 0; k <nums. length-1; k ++) {// control how many rounds are compared
For (int k2 = 0; k2 <nums. length-1-k; k2 ++) {// change the largest element to the last
If (nums [k2]> nums [k2 + 1]) {
// Exchange Element
Temp = nums [k2];
Nums [k2] = nums [k2 + 1];
Nums [k2 + 1] = temp;
}
}
}
System. out. print ("\ n after sorting :");
For (int k = 0; k <nums. length; k ++ ){
System. out. print (+ nums [k] + "");
}
}
}
Bubble Sorting is actually a simple exchange sorting. It is to scan the elements to be sorted from the beginning, compare the Adjacent Elements in sequence during the scanning process, and move the elements with a large keyword value behind. After each sorting, the element with the maximum keyword value will be moved to the end. At this time, write down the position of the element. The next sorting only needs to be compared to this position, until all elements are sorted.
Simply put:
It is to execute a double loop. The number of rounds of comparison is the condition of the outer loop, and the number of comparisons is the condition of the inner loop.