The console displays a sample Java bubble sort process

  • 2020-04-01 03:11:44
  • OfStack

Class: Nums      Authority: public
Methods: main      Authority: public
Parameters: the nums, I, j, num;
Parameter description:
Nums, data type int[], a series of arrays used to store ints;
I, data type int, as the loop variable of the for loop, stores the number of rounds of sort comparison;
J, data type int, as the loop variable of the for loop, stores the number of sort comparisons of the round;
Num, data type int, as a third party variable with two values interchanged.
Method functions:

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 the round comparison;

The first unsorted number in the array is compared with the other Numbers that follow.
If the first unsorted number is smaller than the number compared with it, they are swapped to ensure that the first unsorted number is always the largest of the Numbers compared.
After the loop completes, the sorted results are output with an iterative loop.


public class NumsI{
 public static void main (String [] arge){

 //Defines an array of Numbers of type nums with an int and assigns the initial value;
 int[] nums = new int[]{12,24,34,14,45,17,65,51,25};

 //Indicates the sorting mode and iterates the initial state of the array.
 System.out.println(" Bubble sort demo ");
 System.out.print(" The initial data  ");
  for (int num :nums){
   System.out.print(num + " ");
  }
  System.out.println();  

  //Set up a loop to record the number of comparison rounds;
  for (int i = 0; i < nums.length-1; i++ ){

   //Set a loop to record the number of comparisons in the round of comparisons.    
   for(int j =0;j < nums.length-1-i; j++){

    //Compare the preceding value in the nums[] array with the value following it, and execute the following code block if the latter value is larger.
    if(nums[j]<nums[j+1]){

     //Swap in the nums[] array;
     int num = nums[j];
     nums[j] = nums[j+1];
     nums[j+1] = num; 

     //Outputs the values of the two swap positions;
     System.out.print(nums[j+1] + " and " + nums[j] + " Change the position "+" ");    
    }else{//If there is no swap, print a space to keep the output neat.
     System.out.print("  ");
    }
    //An iterative loop is used to output the results after the sorting is completed.
    for (int num :nums){
     System.out.print(num + " ");
    }
    //The tips were compared;
    System.out.println(" A comparison was made " );
   }

   //The prompts were compared in a round;
   System.out.println(" End of round comparison ");
  }

  //The prompt is relatively complete and the output result is iterated.
  System.out.println(" The completion of ");
  for (int num :nums){
  System.out.print(num +" ");
  }
 }
}


Related articles: