Import Java.util.Random;
public class Bubblesort {
public static void Main (string[] args) {
1. Randomly generate 10 integers within 100
Int[] Arr=new int[10];
Random ran=new random ();
for (int i=0;i<arr.length;i++) {
Arr[i]=ran.nextint (100);
}
2. Bubble sort
Sort (arr);
3. View Final Sort Results
System.out.println (arrays.tostring (arr));
}
Bubble sort
public static void sort (int[] arr) {
Valid Code 1: The first loop indicates the number of times you need to bubble, because the last number left does not need to bubble, so the whole bubbling process needs to be bubbling: arr.length-1 times.
for (int i=0;i<arr.length-1;i++) {
Valid Code 2: The second loop represents the range of data that needs to be bubbled up, because the data that has come out does not need to be bubbling again, so it needs to be excluded.
Because our entire bubbling design idea is that every cycle takes the largest data in the rest of the data to the last place, so the data behind it doesn't need to be bubbling anymore.
So each bubbling range is from the first position to the arr.length-i-1 position.
Arr.length-i-1:arr.length-1 indicates the total number of bubbles required, I indicates the number of times that has been taken, so arr.length-i-1 indicates the number of times left to take.
for (int j=0;j<arr.length-i-1;j++) {
Each bubble needs to compare the current data with the data behind him.
The last data obtained through if (arr[j]>arr[j+1]) is sorted in order from small to large
If you want to sort from a large to a small order, you need to write this: if (arr[j]<arr[j+1])
if (Arr[j]>arr[j+1]) {
If the current data is larger than the data behind it, the two exchange positions, otherwise the position is unchanged.
int TEMP=ARR[J];
ARR[J]=ARR[J+1];
Arr[j+1]=temp;
}
}
}
}
}
Java Foundation------Bubble sort