java 氣泡排序演算法優化
阿新 • • 發佈:2019-01-06
1、氣泡排序優化思想
在文章《JAVA實現氣泡排序演算法》中,我們用常規演算法實現了氣泡排序,在此篇中,我們對氣泡排序演算法進行優化,思想如下:引入一個標誌位,預設為true,如果本次或者本趟遍歷前後資料比較發生了交換,則標誌位設定為true,否則為false;直到又一次資料沒有發生交換,說明排序完成。
2、例項
(1)java程式碼
(2)結果package cn.com.yy; import java.util.Random; public class BubbleSortClient { public static void main(String[] args) { //構造資料 int[] arr = constructDataArray(15); System.out.println("---------排序前-----------"); printArrayData(arr); //氣泡排序 bubbleSort4(arr); System.out.println("---------排序後-----------"); printArrayData(arr); } //構造資料 public static int[] constructDataArray(int length){ int[] arr = new int[length]; Random random = new Random(); for(int i=0;i<length;i++){ arr[i] = random.nextInt(length); } return arr; } /** * 引入標誌位,預設為true * 如果前後資料進行了交換,則為true,否則為false。如果沒有資料交換,則排序完成。 * @param arr */ public static int[] bubbleSort4(int[] arr){ boolean flag = true; int n = arr.length; while(flag){ flag = false; for(int j=0;j<n-1;j++){ if(arr[j] >arr[j+1]){ //資料交換 int temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; //設定標誌位 flag = true; } } n--; } return arr; } //列印資料 public static void printArrayData(int[] arr){ for(int d :arr){ System.out.print(d + " "); } System.out.println(); } }
---------排序前-----------
10 3 9 10 7 1 6 8 12 8 7 14 14 8 1
---------排序後-----------
1 1 3 6 7 7 8 8 8 9 10 10 12 14 14