冒泡排序

package com.jmdf;

import java.util.Arrays;

/**
 * 算法--冒泡排序n个数
 * 复杂度--     (((n-1)+1)*(n-1))/2
 * 最差         (n²-n)/2
 * 最优       1
 *     O(n²)
 */
public class Algorithm {

    public static void main(String[] args) throws Exception {
        int[] a =source();
        System.out.println();
        try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }
        int[] b = sort(a);
        result(b);

    }


public static  int[] source(){
    int[] a ={5,4,3,2,1};
    System.err.print("冒泡排序前:");
    try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }
    for (int i =0;i<a.length;i++){
        System.out.print(+a[i]);
    }
    try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }
        return a;
}

public static int[] sort(int[] sourceArray) throws Exception {
            int count =0;//计数交换次数

            // 对 arr 进行拷贝,不改变参数内容
            int[] arr = Arrays.copyOf(sourceArray, sourceArray.length);

            for (int i = 1; i < arr.length; i++) {
                // 设定一个标记,若为true,则表示此次循环没有进行交换,也就是待排序列已经有序,排序已经完成。
                boolean flag = true;

                for (int j = 0; j < arr.length - i; j++) {
                    if (arr[j] > arr[j + 1]) {

                        int tmp = arr[j];
                        arr[j] = arr[j + 1];
                        arr[j + 1] = tmp;
                        System.err.print("交换第"+(++count)+"次数:");
                        try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }
                        for (int t =0;t<arr.length;t++){
                            System.out.print(+arr[t]);
                        }
                        System.out.println();
                        try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }
                        flag = false;
                    }
                }

                if (flag) {
                    break;
                }
            }

            return arr;
        }

    public static  int[] result(int[] b){

        System.err.print("冒泡排序后:");
        try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }
        for (int i =0;i<b.length;i++){
            System.out.print(b[i]);
        }
        try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }
        return b;
    }

}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值