import java.text.SimpleDateFormat;
import java.util.Date;
public class BubbleSort {
// 冒泡排序的时间复杂度是:O(n^2)
public static void main(String[] args) {
// int[] arr = {4, 34, 19, 1, 9 ,-1};
// 创建一个含1000000个随机数的数组
int[] arr = new int[1000000];
for (int i = 0; i < 1000000; i++) {
// Math.random()产生0-1之间的随即小数,需要乘以范围的大小指定范围
arr[i] = (int) (Math.random() * 1000000);
}
// System.out.println("排序前的数组是:" + Arrays.toString(arr));
// 标准化时间输出格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss sss");
Date date1 = new Date();
String strTime1 = sdf.format(date1);
System.out.println("排序前的时间为:" + strTime1);
// 进行排序
bubbleSort(arr);
// System.out.println("排序后的数组是:" + Arrays.toString(arr));
Date date2 = new Date();
String strTime2 = sdf.format(date2);
System.out.println("排序后的时间为:" + strTime2);
}
// 将冒泡排序封装成一个方法
public static void bubbleSort(int[] arr) {
int temp;
for (int i = arr.length - 1; i > 0; i--) {
// 标识是否进行了交换
boolean flag = false;
// 判断arr[j]数字和arr[j + 1]数字的大小
for (int j = 0; j < i; j++) {
if (arr[j] > arr[j + 1]) {
flag = true;
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
// 如果这次的排序中不发生交换,结束冒泡排序
if (!flag) {
break;
}
}
}
}
algorithm:冒泡排序
最新推荐文章于 2025-05-09 17:11:59 发布