今天学习了一个冒泡算法与大家分享一下,不足的地方请大家指教
两种循环体,结果都是由小到大排列
一:小数左沉
//冒泡循环
public class Bubble_test {
public static void main(String[] args) {
method_b();
}
// 冒泡循环体,小数左沉
public static void method_b() {
int[] a = method();// 调用随机产生数组方法
int num;
for (int i = 0; i < a.length - 1; i++) {// 控制循环层次
for (int j = i + 1; j < a.length; j++) {// 循环一轮后最小值在最左侧,每次循环找出当前循环的最小值
if (a[i] > a[j]) {// 判断当前数组与下一个数组的大小,如果当前的大则交换;
num = a[i];
a[i] = a[j];
a[j] = num;
}
}
}
// 遍历打印数组
for (int z = 0; z < a.length; z++) {
System.out.println(a[z]);
}
}
// 获取随机数组
public static int[] method() {
Random r = new Random();// 产生随机数
int[] a = new int[10];// 动态创建数组
// 遍历,在数组中填入十个随机数
for (int j = 0; j < a.length; j++) {
a[j] = r.nextInt(a.length);
}
System.out.println();
// System.out.print(Arrays.toString(a));
return a;// 方法返回值
}
}
二 大数右浮
public class Bubble_test02 {
public static void main(String[] args) {
methodtes();//在主程序中实现循环体
}
//冒泡循环体,大数冒出排序
public static void methodtes() {
Bubble_test arr= new Bubble_test();//创建对象,用来产生随机数组
int num;
int[] i = arr.method();//调用了Bubble_test类的method(产生随机数组)方法
for(int a=0;a<i.length-1;a++) {//控制循环层次
for(int s=0;s<i.length-a-1;s++) {//循环一轮之后找出最大值右浮,最右侧为最大值,下一次循环少一次,说以-a
if(i[s]>i[s+1]) {
num = i[s];
i[s]=i[s+1];
i[s+1]=num;
}
}
}
//遍历打印数组
for(int t=0;t<i.length;t++) {
System.out.println(i[t]);
}
}
}

浙公网安备 33010602011771号