In Java, arrays are the most commonly used tools, as described below.
Three ways to declare an array:
1. Array type [] array name =new array type [array length];
2. Array type [] array name ={array 0, array 1, array 2, array 3,....};
3. Array type [] array name =new array type []{array 0, array 1, array 2,...};
Here are three ways to illustrate one by one:
String[] Number=new string[5]; Directly declares the length of an array
Int[] num={20,12,60,51,85,2,3,12,0}; Directly enumerate the data in the array
Double[] Nums=new double[]{12,20,30,10}; Enumerating the data in an array
And that's the point I'm going to talk about today.
Bubble ordering of classical algorithms in Java
Principle: compare two adjacent elements and exchange large value elements to the right end.
Idea: Compare adjacent two numbers in turn, place decimals in front, and large numbers on the back. That is, in the first trip: first compare the 1th and 2nd numbers, put the decimals before the large number. Then compare the 2nd and 3rd numbers, place the decimal before the large number, and then continue until you compare the last two numbers, put the decimals before the decimal, and put the large number behind. Repeat the first step until all sorts are complete.
Instance diagram of Bubble sort
The process of bubbling the sort is simple, which is to compare the first record's keyword with the keyword of the second record, if the latter is smaller than the previous one, and then compare the second and third, and so on. Compared to the last trip, the largest one has been placed in the final position, so that the number of front N-1 can be recycled.
Let's take a look at how the code is implemented
Punlic static void Main (string[] args) {
/**
* Three ways to declare an array
*/
String[] Number=new string[5]; Directly declares the length of an array
Double[] Nums=new double[]{12,20,30,10}; Enumerating the data in an array
Int[] num={20,12,60,51,85,2,3,12,0}; Directly enumerate the data in the array
System.out.println ("Order of the array before sorting =====================");
for (int item:num) {
System.out.print ("+item");
}
/**
* Bubble Sort
* Swap with Intermediate variable temp
* @param num
*/
for (int i = 0; i < num.length; i++) {///Outer loop control sort trip number
for (int j = 0; J < Num.length-1-i; J + +) {//Inner loop controls how many times each trip is sorted
if (Num[j]>num[j+1]) {//If the latter number is less than the previous number
int TEMP=NUM[J];
NUM[J]=NUM[J+1];
Num[j+1]=temp;
}
}
}
System.out.println ();
System.out.println ("Order of the sorted array =====================");
for (int item:num) {
System.out.print ("+item");
}
}
Console Print Results:
So far, the bubble sort of classic algorithms in Java is basically over.
Welcome to comment or point out the inadequacies of the place!!!
Bubble ordering of classical algorithms in Java