Class:Nums Permission:public
Method: main permission: public
Parameters: nums,i,j,num;
Parameter introduction:
nums, the data type int[], is used to store a series of arrays of int type;
i, the data type int, as the loop variable of the for loop, stores the number of rounds for sorting and comparison;
j, data type int, as a loop variable for the for loop, storing the number of times the round sort and comparison is performed;
num, data type int, as a third-party variable that interchanges between two values.
Method Function:
Define an int[] array;
Set a loop variable i to record the number of comparison rounds;
Set a loop variable j to record the number of comparisons in this round of comparisons;
Compare the first number that is not sorted in the array with other numbers that follow;
If the first number that is not sorted is smaller than the number that is compared with it, exchange their positions to ensure that the first number that is not sorted is always the largest number that has participated in the comparison;
After the loop is completed, the sort results are output using the iterative loop.
The code copy is as follows:
public class NumsI{
public static void main (String [] arge){
//Define an int number with type array nums and assign an initial value;
int[] nums = new int[]{12,24,34,14,45,17,65,51,25};
// Prompt the sorting method and use iterative output to the initial state of the array;
System.out.println("Bubble sorting demonstration");
System.out.print("initial data");
for (int num :nums){
System.out.print(num + " ");
}
System.out.println();
//Set a cycle to record the number of comparison rounds;
for (int i = 0; i < nums.length-1; i++ ){
//Set a cycle to record the number of comparisons in this round of comparison;
for(int j =0;j < nums.length-1-i; j++){
//Compare the previous value in the nums[] array with the value after it. If the subsequent value is larger than it, execute the following code block;
if(nums[j]<nums[j+1]){
//Swap the nums[] array;
int num = nums[j];
nums[j] = nums[j+1];
nums[j+1] = num;
//Output the values of two exchange positions;
System.out.print(nums[j+1] + "and" + nums[j] + "change position"+"");
}else{// If there is no exchange, print spaces to keep the output format neat;
System.out.print("");
}
//Use iterative loop to output the result after this sorting is completed;
for (int num :nums){
System.out.print(num + " ");
}
//A comparison was made;
System.out.println("A comparison was made");
}
//A prompted to make a round of comparison;
System.out.println("This round of comparison ends");
}
//The prompt is relatively complete and the iterative output results are used;
System.out.println("complete");
for (int num :nums){
System.out.print(num +" ");
}
}
}