改進的冒泡排序算法二
阿新 • • 發佈:2017-09-14
put logs 數組 img 對比 for algorithm ati con
/** * Project Name:Algorithm * File Name:BubbleSortImprove2.java * Package Name: * Date:2017年9月14日上午11:30:48 * Copyright (c) 2017, [email protected] 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"); } } }
改進的冒泡排序算法二