示例代码如下
package interview;
import java.util.Arrays;
import java.util.Random;
//冒泡排序法实现10个100内的随机数字的排序
public class BubbleSort {
public static void main(String[] args) {
//数据准备
int[] arr = new int[10];
for (int i = 0; i < arr.length; i++) {
Random random = new Random();
arr[i] = random.nextInt(100);
}
System.out.println(Arrays.toString(arr));
System.out.println("************冒泡排序开始**************");
bubbleSort(arr);
System.out.println("************冒泡排序开始**************");
System.out.println(Arrays.toString(arr));
}
//冒泡排序
public static void bubbleSort(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
System.out.println(Arrays.toString(arr));
}
}
}
代码执行结果如下:
[91, 69, 11, 90, 29, 25, 77, 63, 47, 37]
************冒泡排序开始**************
[69, 11, 90, 29, 25, 77, 63, 47, 37, 91]
[11, 69, 29, 25, 77, 63, 47, 37, 90, 91]
[11, 29, 25, 69, 63, 47, 37, 77, 90, 91]
[11, 25, 29, 63, 47, 37, 69, 77, 90, 91]
[11, 25, 29, 47, 37, 63, 69, 77, 90, 91]
[11, 25, 29, 37, 47, 63, 69, 77, 90, 91]
[11, 25, 29, 37, 47, 63, 69, 77, 90, 91]
[11, 25, 29, 37, 47, 63, 69, 77, 90, 91]
[11, 25, 29, 37, 47, 63, 69, 77, 90, 91]
************冒泡排序开始**************
[11, 25, 29, 37, 47, 63, 69, 77, 90, 91]