冒泡排序
自己实现
public class MaoPao {
public static void main(String[] args) {
int[] temp = new int[]{1,3,5,2,8,9,4,10};
System.out.println(maoPao(temp));
}
public static String maoPao(int[] o){
int length = o.length;
System.out.println("数组长度: "+length);
int temp;
int cishu = 0;
for (int i = 0; i < length; i++) {
for (int j = 0; j < length-i-1; j++) {
if (o[j] > o[j+1]){
temp = o[j+1];
o[j+1] = o[j];
o[j] = temp;
cishu++;
}
}
System.out.println("第"+i+"次排序:"+Arrays.toString(o));
}
System.out.println("运算次数:"+cishu);
return Arrays.toString(o);
}
}
封装api实现
API设计
![在这里插入图片描述](https://img-blog.csdnimg.cn/82431a3b265444d9a05a309a2db197d8.png)
- 冒泡排序的所需要的方法,对外只提供一个sort方法
public class Bubble {
public static void sort(Comparable[] a){
for (int i = a.length-1; i > 0 ; i--) {
for (int j = 0; j < i; j++) {
if(greater(a[j],a[j+1])){
exch(a,j,j+1);
}
}
}
}
private static Boolean greater(Comparable v,Comparable w){
int i = v.compareTo(w);
if(i > 0){
return true;
}else {
return false;
}
}
private static void exch(Comparable[] a,int i, int j){
Comparable temp;
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
public class BubbleTest {
public static void main(String[] args) {
Integer[] o = {1,5,3,6,2,8};
Bubble.sort(o);
System.out.println(Arrays.toString(o));
}
}
性能
-
算法分析
-
比较次数
(N-1)+(N-2)+(N-3)+...+2+1
=
((N-1)+1)*(N-1)/2
=
N^2/2-N/2
;
交换次数
(N-1)+(N-2)+(N-3)+...+2+1
=
((N-1)+1)*(N-1)/2
=
N^2/2-N/2
;
总的次数
(N^2 /2-N/2)+(N^2 /2-N/2)
=
N^2-N
;