Class: Nums Permissions: Public
Method: Main Permission: Public
Parameters: Nums,i,j,num;
Parameter introduction:
Nums, data type int[], used to store a series of arrays of type int;
I, the data type int, as the loop variable of the For loop, stores the number of rotations for the sort comparison;
j, data type int, as a loop variable for a for loop, that stores the number of times the order of the wheel is compared;
num, the data type int, as a third-party variable of two-value interchange.
Method Features:
Defines a int[] array;
Set a loop variable I to record the number of rounds;
Set a loop variable J to record the number of comparisons in the wheel comparison;
Compares the first number that is not sorted in the array with the other numbers that follow;
If the first number that is not sorted is smaller than the number compared to him, the position is exchanged to ensure that the first number of unsorted is always the largest in the number of comparisons;
After the loop completes, the result is sorted by iteration loop output.
Copy Code code as follows:
public class numsi{
public static void Main (String [] arge) {
Defines an int with an array of nums, and assigns an initial value;
int[] nums = new int[]{12,24,34,14,45,17,65,51,25};
Prompts the sort mode and iterates the initial state of the array output;
System.out.println ("bubble sort Demo");
System.out.print ("initial data");
for (int num:nums) {
System.out.print (num + "");
}
System.out.println ();
Set up a loop to record the number of rounds compared;
for (int i = 0; i < nums.length-1; i++) {
Set a loop to record the number of comparisons in the wheel comparison;
for (Int J =0;j < Nums.length-1-i; J + +) {
Compares the previous value in the nums[] array with the value after it, and executes the following block of code if the subsequent value is larger than it;
if (Nums[j]<nums[j+1]) {
Exchange in the nums[] array;
int num = nums[j];
NUMS[J] = nums[j+1];
NUMS[J+1] = num;
Output the value of two swap positions;
System.out.print (Nums[j+1] + "and" + nums[j] + "change position" + "");
}else{//Print Spaces If no exchange is used to keep the output format neat;
System.out.print ("");
}
The result of the completion of this order is obtained by iterative cyclic output;
for (int num:nums) {
System.out.print (num + "");
}
A comparison was made at the prompt;
System.out.println ("a comparison");
}
Prompted a round of comparisons;
System.out.println ("The comparison of this round is over");
}
The result is more complete and iterative output.
System.out.println ("finished");
for (int num:nums) {
System.out.print (num + "");
}
}
}