改进的冒泡排序算法一

改进的冒泡排序算法一

/**
 * Project Name:Algorithm
 * File Name:BubbleSortImprove1.java
 * Package Name:
 * Date:2017年9月14日上午11:07:21
 * Copyright (c) 2017, chenzhou1025@126.com All Rights Reserved.
 *
 */
/**
 * Project Name:Algorithm
 * File Name:BubbleSortImprove1.java
 * Package Name:
 * Date:2017年9月14日上午11:07:21
 * Copyright (c) 2017, 2692613726@qq.com All Rights Reserved.
 *
 */

/**
 * ClassName:BubbleSortImprove1 
 * Function: 改进的冒泡排序算法, 测试数据集:6 3 5 7 0 4 12. 
 * Reason:     本例的数据集,在第4次就已经排好序了,所以没必要再进行第5、6次的排序了。
 *             设置一个bool变量,判断本次循环有没有元素之间交换位置,如果没有,则说明已经排好序了,
 *             退出循环即可
 *              
 * Date:     2017年9月14日 上午11:07:21 
 * @author   michael
 * @version  
 * @since    JDK 1.7
 * @see      
 */
public class BubbleSortImprove1 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String input = "";
        while (sc.hasNext()) {
            input = sc.nextLine();
            System.out.println("输入值:" + input);
            long startTime = System.currentTimeMillis();
            String[] str = input.split(" ");
            int[] arr = new int[str.length];
            // 字符串数组转化成int数组
            for (int i = 0; i < str.length; i++) {
                arr[i] = Integer.parseInt(str[i]);
            }
            for (int i = 0; i < arr.length - 1; i++) {
                boolean isChanged=false;
                for (int j = 0; j < arr.length - 1; j++) {
                    int temp;
                    if (arr[j] > arr[j + 1]) {
                        temp = arr[j];
                        arr[j] = arr[j + 1];
                        arr[j + 1] = temp;
                        isChanged = true;
                    }
                    
                }
                if(!isChanged)
                    break;    
                System.out.println();
                System.out.print("第" + (i + 1) + "次循环结果:");
                for (int j = 0; j < arr.length; j++) {
                    System.out.print(arr[j]);
                }
            }
            long endTime = System.currentTimeMillis();
            System.out.println();
            System.out.println();
            System.out.println("最终排序结果:");
            for (int j = 0; j < arr.length; j++) {
                System.out.print(arr[j]);
            }
            System.out.println("程序运行时间:" + (endTime - startTime) + "ms");
        }
    }
}

 

posted on 2017-09-14 11:20 Michael2397 阅读(...) 评论(...) 编辑 收藏

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值