冒泡排序
例:1,5,6,3,20,0这七个数从小到大进行排序,则先把1,5进行比较,1<5则不换位子;再把5,6进行比较,5<6,不换位子;6,3进行排序,因为6<3则进行变换得:1,5,3,6,20,0.再6,20 进行比较,不进行变化。20,0进行比较,进行变化得1,5,3,6,0,20。此时,最大的值得到确定,故下一次排序久不要考虑最后一个了,只要考虑前六个即可。这种方法叫做冒泡排序。
时间复杂度的分析
由于对n个数进行冒泡排序,需要两个for循环,故时间复杂度为O(n2)。
代码实现
public class BubbleSort {
public static void main(String[] args) {
int[] ints = new int[]{
1,2,3,6,5,4,7,8
};
bubbleSort(ints);
//通过Arrays的toString将数组转换成为字符串。
System.out.println(Arrays.toString(ints));
}
/**
* 定义冒泡排序方法,从小到大排。
* @param arr
*/
public static void bubbleSort(int[] arr){
int temp;
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]){
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
}
但是,它本身还可以进行优化。比如我要是输入的数组为[1,2,3,4,5,6]理论上是已经排序完全了,无需进行判断排序。但是,这个算法还没有体现出来。故可以进行改进。
优化排序
public static void bubbleSort(int[] arr){
int count = 0;
int temp;
boolean flag = false;
for (int i = 0; i < arr.length -1; i++) {
count++;
for(int j = 0; j < arr.length -1 - i ;j++){
if(arr[j] > arr[j + 1]){
//当循环完一次之后,如果没有进入过if判断,说明已经是排序完毕了。
flag = true;
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
//如果它排序完毕了,直接返回,之前的for也不执行了。
if(!flag){
System.out.println("实际执行的次数:" + count);
break;
}else{
//如果 flag = true 则需要进行重置。
flag = false;
}
}
}
测试结果如下:
符合测试预期。
实际花费时间统计
用50000个数进行统计
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* FileName: BubbleSort
*
* @Author:luguobao Date: 2020/4/2212:24
* Description:
* History:
* <author> <time> <version> <desc>
* 作者姓名 修改时间 版本号 描述
*/
public class BubbleSort {
public static void main(String[] args) {
int[] ints = new int[50000];
for (int i = 0; i < ints.length; i++) {
//*10000是为了数据分散。
ints[i] = (int)(Math.random() * 10000);
}
//定义日期输出格式
final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
final String format = simpleDateFormat.format(date);
System.out.println("排序前时间为" + format);
bubbleSort(ints);
Date date1 = new Date();
final String format1 = simpleDateFormat.format(date1);
System.out.println("排序后时间为" + format1);
//bubbleSort(ints);
//通过Arrays的toString将数组转换成为字符串。
}
/**
* 定义冒泡排序方法,从小到大排。
* @param arr
*/
public static void bubbleSort(int[] arr){
int temp;
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]){
//当循环完一次之后,如果没有进入过if判断,说明已经是排序完毕了。
flag = true;
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
//如果它排序完毕了,直接返回,之前的for也不执行了。
if(!flag){
break;
}else{
//如果 flag = true 则需要进行重置。
flag = false;
}
}
}
}
结果如下图:
所以,冒泡算法还是挺慢的。
由于Arrays类中也有sort()算法,故用其测试了一下。
//代替bubbleSort(ints);
Arrays.sout(ints);
结果为:
故如果可以用别的算法可以优先使用其他算法。