排序算法——冒泡排序
大纲目录
排序算法简介
一、基本介绍
- 冒泡排序(Bubble Sorting)的基本思想是:通过对待排序序列从前向后(从下标较小的元素开始),依次比较相邻元素的值,若发现逆序则交换,使值较大的元素逐渐从前移向后部,就象水底下的气泡一样逐渐向上冒。
- 因为排序的过程中,各元素不断接近自己的位置,如果一趟比较下来没有进行过交换,就说明序列有序,因此要在排序过程中设置一个标志flag判断元素是否进行过交换。从而减少不必要的比较。
- 前一轮的最终交换位置为本轮的最终截至位置-1
二、冒泡排序图解

三、源码
public class BubbleSort {
public static void main(String[] args) {
int[] arr = new int[80000];
for(int i =0; i < 80000;i++) {
arr[i] = (int)(Math.random() * 8000000);
}
System.out.println("80000条数据排序开始:");
long start1 = System.currentTimeMillis();
bubblesort2(arr);
long end1 = System.currentTimeMillis();
System.out.println("80000条数据排序结束:");
System.out.println("80000条数据排序耗时:"+(end1-start1));
}
public static void bubblesort1(int[] arr){
int temp = 0;
for(int i=0;i<=arr.length-1;i++){
for(int j=0;j<=arr.length-2-i;j++){
if(arr[j]>arr[j+1]){
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1]=temp;
}
}
}
}
public static void bubblesort2(int[] arr){
int temp = 0;
Boolean flag = true;
int boundary = arr.length-2;
int lastLocation = 0;
for(int i=0;i<=arr.length-1;i++){
for(int j=0;j<=boundary;j++){
if(arr[j]>arr[j+1]){
flag = true;
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1]=temp;
lastLocation = j-1;
}
}
boundary = lastLocation;
if(!flag){
break;
}
}
}
}