-
public interface Sort {
-
public boolean sort(int[] arr);
-
}
-
package com.lhk.sortDemo;
-
-
import java.util.Arrays;
-
-
public class BubbleSort implements Sort{
-
-
public boolean sort(int[] arr) {
-
if(arr == null){
-
return false;
-
}
-
-
if(arr.length <= 1){
-
return true;
-
}
-
boolean flag = true;
-
int length = arr.length;
-
for(int i = 0; i < length - 1 && flag; i++){
-
flag = false;
-
for(int j = 0; j < length - i - 1; j++){
-
if(arr[j] > arr[j + 1]){
-
swap(arr, j , j + 1);
-
flag = true;
-
}
-
}
-
System.out.println(" sort num =" + (i+1) +" :" + Arrays.toString(arr));
-
}
-
return true;
-
}
-
-
-
private void swap(int[] arr, int start, int end){
-
// 安全性判断就不做了。。
-
int temp = arr[start];
-
arr[start] = arr[end];
-
arr[end] = temp;
-
}
-
-
}
-
public class SortDemo1 {
-
-
/**
-
* @param args
-
*/
-
public static void main(String[] args) {
-
-
int[] arr = {1,4,6,8,1,11,34,2,67,5,1,9,10,13,2,4,5};
-
-
// 冒泡排序
-
Sort sort = new BubbleSort();
-
-
System.out.println("before sort :" + Arrays.toString(arr));
-
-
sort.sort(arr);
-
-
-
System.out.println("after sort :" + Arrays.toString(arr));
-
}
-
-
}
结果:
before sort :[1, 4, 6, 8, 1, 11, 34, 2, 67, 5, 1, 9, 10, 13, 2, 4, 5]
sort num =1 :[1, 4, 6, 1, 8, 11, 2, 34, 5, 1, 9, 10, 13, 2, 4, 5, 67]
sort num =2 :[1, 4, 1, 6, 8, 2, 11, 5, 1, 9, 10, 13, 2, 4, 5, 34, 67]
sort num =3 :[1, 1, 4, 6, 2, 8, 5, 1, 9, 10, 11, 2, 4, 5, 13, 34, 67]
sort num =4 :[1, 1, 4, 2, 6, 5, 1, 8, 9, 10, 2, 4, 5, 11, 13, 34, 67]
sort num =5 :[1, 1, 2, 4, 5, 1, 6, 8, 9, 2, 4, 5, 10, 11, 13, 34, 67]
sort num =6 :[1, 1, 2, 4, 1, 5, 6, 8, 2, 4, 5, 9, 10, 11, 13, 34, 67]
sort num =7 :[1, 1, 2, 1, 4, 5, 6, 2, 4, 5, 8, 9, 10, 11, 13, 34, 67]
sort num =8 :[1, 1, 1, 2, 4, 5, 2, 4, 5, 6, 8, 9, 10, 11, 13, 34, 67]
sort num =9 :[1, 1, 1, 2, 4, 2, 4, 5, 5, 6, 8, 9, 10, 11, 13, 34, 67]
sort num =10 :[1, 1, 1, 2, 2, 4, 4, 5, 5, 6, 8, 9, 10, 11, 13, 34, 67]
sort num =11 :[1, 1, 1, 2, 2, 4, 4, 5, 5, 6, 8, 9, 10, 11, 13, 34, 67]
after sort :[1, 1, 1, 2, 2, 4, 4, 5, 5, 6, 8, 9, 10, 11, 13, 34, 67]
冒泡排序是一种效率低下的排序方法,在数据规模很小时,可以采用。数据规模比较大时,最好用其它排序方法。