Java array sort sample share

  • 2020-04-01 03:12:06
  • 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 Nums {
 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,4,45,17,65,51,25};

  //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++){

    //The first unsorted number in the array is compared to the other Numbers that follow, and the following block of code is executed if the other Numbers are larger.
    if(nums[j] < nums[j+1]){

     //The first unsorted number is exchanged with a larger number to ensure that the first unsorted number is always the largest.
     int num = nums[j];
     nums[j] = nums[j+1];
     nums[j+1] = num;
    }
   } 
  }//Sorting done;

  //After sorting the output with the iterative loop
  for(int num :nums){
   System.out.print(num + " ");
  }
 }
}


Related articles: