2.1 冒泡排序(Bubble Sorting)
本文最后更新于 2024-07-06,文章内容可能已经过时。
2.1 冒泡排序(Bubble Sorting)
一. 定义
冒泡排序(Bubble Sorting)的基本思想是:通过对待排序序列从前向后(从下标较小的元素开始),依次比较相邻元素的值,若发现逆序则交换,使值较大的元素逐渐从前移向后部,就象水底下的气泡一样逐渐向上冒。
因为排序的过程中,各元素不断接近自己的位置,如果一趟比较下来没有进行过交换,就说明序列有序,因此要在排序过程中设置一个标志flag判断元素是否进行过交换。
二. 代码实现
/**
* desc 冒泡排序
* @author GreyPigeon mail:2371849349@qq.com
* @since 2024-01-12-9:47
**/
public class BubbleSort {
public static void main(String[] args) {
//创建要给80000个的随机的数组
int[] arr = new int[80000];
for(int i =0; i < 80000;i++) {
arr[i] = (int)(Math.random() * 8000000); //生成一个[0, 8000000) 数
}
//计算时间
Date date1 = new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String date1Str = simpleDateFormat.format(date1);
System.out.println("排序前的时间是:"+ date1Str);
//测试冒泡排序
bubbleSort(arr);
Date date2 = new Date();
String date2Str = simpleDateFormat.format(date2);
System.out.println("排序后的时间是:"+ date2Str);
}
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;
}
}
if (!flag) { //在一趟排序中,一次交换都没有发生过
break;
}else{
flag = false; //重置flag,进行下次判断
}
}
}
}
- 感谢你赐予我前进的力量
赞赏者名单
因为你们的支持让我意识到写文章的价值🙏
本文是原创文章,采用 CC BY-NC-ND 4.0 协议,完整转载请注明来自 程序员Graypigeon
评论
匿名评论
隐私政策
你无需删除空行,直接评论以获取最佳展示效果