Arrays of Java data structures (2)
Bubble sort:
/**
*To sort n numbers, a total of n-1 times are sorted, and the sorting times of each I time is (n-1). Therefore, double loop statements can be used. The outer layer controls the number of cycles, and the inner layer controls the number of cycles per trip.
*
* @author Memorial
*
*/
public class BubbleSort {
public static void main(String[] args) {
int a[] = { 25,354,6,7,78,456,5,234,67,443,423,452 };
For (int i = 0; I < a.length - 1; I + +) {/ / outer loop controls the number of sorting times
for (int j = 0; j < a.length - i - 1; j++) {
//The inner loop controls how many times to sort each trip
//Swap small values to the front
if (a[j] > a[j + 1]) {
int temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
System. out. Print ("the" + (I + 1) + "secondary sorting result:");
//List the data sorted each time
for (int x = 0; x < a.length; x++) {
System. out. print(a[x] + "t");
}
System. out. println(" ");
}
System. out. Print ("final sorting result:");
for (int x = 0; x < a.length; x++) {
System. out. print(a[x] + "t");
}
}
}
Output:
The first sorting result: 25 6 7 78 354 5 234 67 443 423 452 456
The second sorting result: 6 7 25 78 5 234 67 354 423 443 452 456
The third sorting result: 6 7 25 5 78 67 234 354 423 443 452 456
The fourth sorting result: 6 7 5 25 67 78 234 354 423 443 452 456
The 5th sorting result: 6 5 7 25 67 78 234 354 423 443 452 456
The 6th sorting result: 5 6 7 25 67 78 234 354 423 443 452 456
The 7th sorting result: 5 6 7 25 67 78 234 354 423 443 452 456
The 8th sorting result: 5 6 7 25 67 78 234 354 423 443 452 456
The 9th sorting result: 5 6 7 25 67 78 234 354 423 443 452 456
The 10th sorting result: 5 6 7 25 67 78 234 354 423 443 452 456
The 11th sorting result: 5 6 7 25 67 78 234 354 423 443 452 456
Final ranking result: 5 6 7 25 67 78 234 354 423 443 452 456