1、冒泡处理(将大的沉入到尾部,或者将小的沉入到尾部)。
2、冒泡处理,需要注意的点是可以提前结束循环,当一次循环都没发生时,将会提前退出循环,节约时间
import java.text.SimpleDateFormat;
import java.util.Date;
public class BubbleSortDemo {
public static void main(String[] args) {
int arr[] = new int[80000];
for (int i = 0; i < 80000; i++) {
arr[i] = (int)(Math.random()*80000);
}
Date date1 = new Date();
// 进行格式化输出,时间,测试代码程序的快慢
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String s1 = simpleDateFormat.format(date1);
System.out.println("排序前:"+s1);
bubbleSort(arr);
// 测试冒泡程序
Date date2 = new Date();
String s2 = simpleDateFormat.format(date2);
System.out.println("排序后:"+s2);
// 冒泡6秒
// System.out.println(Arrays.toString(arr));
}
public static void bubbleSort(int[] arr) {
// 第一趟排序,就是将最大的数排在最后
int temp = 0; // 临时变量
boolean flag = false;// 判断是否有序
// 确定几位数
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - 1 - i; j++) {
// 如果前面的数比后面的数大,则交换
if (arr[j] > arr[j + 1]) {
flag = true;
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
// System.out.println("第" + (i + 1) + "趟排序后的数组:");
// System.out.println(Arrays.toString(arr));
if (flag == false)// 一次排序都没发生,提前结束冒泡处理
{
break;
} else {
flag = false; // 重新置为空
}
}
}
}
该代码示例展示了如何用Java实现冒泡排序算法,并通过设置标志变量`flag`来优化冒泡排序,当数组已经有序时可以提前结束排序,从而提高效率。代码中还使用了`Date`和`SimpleDateFormat`来计算和显示排序前后的时间差,以评估程序性能。
222

被折叠的 条评论
为什么被折叠?



