冒泡排序(java实现)

a.基本思想:每一次排序后找到最大的一个数

  1. 对于数组中的各数据,依次比较相邻的两个元素的大小
  2. 如果前面的数据大于后面的数据,交换着两个数据,一轮比较可以得到最小的数据。
  3. 使用同样的方法对剩下的数据进行比较,最后全部排好序
  4. 双重循环,第一个控制的是次数,第二个控制的结果的交换

2.举例实现:
假设有n个数,对其进行冒泡排序,从小到大输出结果

package com.linchong.bubblesort;

/**
 * 
 * @version:
 * @author:linchong
 * @date:2018年6月2日 下午3:09:47
 * @Description:(方法功能描述)
 * 演示冒泡排序
 * 基本思想:每一次排序后找到最大的一个数
 * 对于数组中的各数据,依次比较相邻的两个元素的大小
 * 如果前面的数据大于后面的数据,交换着两个数据,一轮比较可以得到最小的数据。
 * 使用同样的方法对剩下的数据进行比较,最后全部排好序
 */
public class BubbleSort {

    static final int SIZE = 10;

    public static void bubbleSort(int[] a){
        int temp;
        for(int i=1;i<a.length;i++){

            for(int j=0;j<a.length-1;j++){
                if(a[j]>a[j+1]){
                    temp = a[j];
                    a[j] = a[j+1];
                    a[j+1] = temp;
                }
            }
            System.out.println("本次排序后的结果是:");
            for (int k : a) {
                System.out.print(k+" ");
            }
            System.out.print("\n");
        }
    }

    public static void main(String[] args) {
        int[] array = new int[SIZE];
        int i;
        for(i=0;i<SIZE;i++){
            array[i] = (int)(100+Math.random()*(100+1));
        }
        System.out.println("排序前的数组为:");
        for (int j : array) {
            System.out.print(j+" ");
        }
        System.out.printf("\n");
        bubbleSort(array);
        System.out.println("排序后的数组为:");
        for (int k : array) {
            System.out.print(k+" ");
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

罚站的孩子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值