定义接口:
public interface Algorithm {
/**冒泡排序*/void bubble(int[] arr);
}
实现类:
package algorithm.sort.imp;
import algorithm.sort.Algorithm;
public class AlgorithmImpl implements Algorithm {
//冒泡排序
@Override
public void bubble(int[] arr) {
//1.使用外层循环来控制比较的轮数
for(int i = 1; i < arr.length; i++){
//使用标志位来表示该轮比较中是否发生过元素的交换
boolean flag = true;
//2.使用内层循环来控制比较的元素下标范围,也就是比较的次数
for(int j = 0; j < arr.length-i; j++){
//3.若左边的元素大于右边的元素,则交换两个元素的位置
if(arr[j] > arr[j+1]){
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
flag = false;
}
}
//根据flag的数值来判断是否发生过交换
if(flag){
break;
}
}
}
}
测试:
package test;
import algorithm.sort.Algorithm;
import algorithm.sort.imp.AlgorithmImpl;
public class Test1 {
public static void main(String[] args) {
int[] brr = {20, 10, 25, 5, 15, 30, 8, 20, 12};
Algorithm algorithm = new AlgorithmImpl();
algorithm.bubble(brr);
//打印结果
System.out.print("排序后的结果是:");
for(int i = 0; i < brr.length; i++){
System.out.print(brr[i] + " ");
}
}
}