改进的冒泡排序算法二

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

/**
 * ClassName:BubbleSortImprove2 
 * Function: 改进的冒泡排序算法, 测试数据集:6 3 5 7 0 4 12. 
 * Reason:    (基于改进方法一的基础上) 在对数据集进行从小到大排序的过程中,在进行第一次排序后,发现后面几位数字基本有序了,没必要再做对比。 
 *              如果R[0..i]已是有序区间,上次的扫描区间是R[i..n],记上次扫描时最后 一次执行交换的位置为lastSwapPos,
 *             则lastSwapPos在i与n之间,不难发现R[i..lastSwapPos]区间也是有序的,否则这个区间也会发生交换;
 *             所以下次扫描区间就可以由R[i..n] 缩减到[lastSwapPos..n]。
 * Date:     2017年9月14日 上午11:30:48 
 * @author   michael
 * @version  
 * @since    JDK 1.7
 * @see      
 */
public class BubbleSortImprove2 {
    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]);
            }
            int pos = arr.length-1;
            boolean isChange = false;
            for (int i = 0; i < arr.length - 1; i++) {
                for (int j = 0; j < pos; j++) {
                    int temp;
                    if (arr[j] > arr[j + 1]) {
                        temp = arr[j];
                        arr[j] = arr[j + 1];
                        arr[j + 1] = temp;
                        isChange = true;
                    }
                    if(!isChange){
                        pos = j;
                        continue;
                    }
                }
                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");
        }
    }
}

原文地址:https://www.cnblogs.com/Michael2397/p/7519882.html