java编写冒泡排序

定义接口:

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] + " ");
}

}


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值