基本思想:算法
排序的一組數中,對當前還未排好序的範圍內的所有數,自上而下對相鄰的倆個數依次進行比較ide
和調整,讓較大的數下沉,較小的數往上冒。即:每當倆相鄰的數比較後發現他們的排序與排序的要求相反時,就將他們交換。spa
冒泡排序示例:3d
算法的實現:code
public class BubbleSort2 { public static void main(String[] args) { int[] a = {12,43,65,72,87,21,98,21,911,679,22,4,1,8,2456,32}; bubbleSort(a,a.length); for(int i=0; i<a.length; i++){ System.out.print(a[i]+" "); } } public static void bubbleSort(int[] a,int n){ int temp; for(int i=0; i<n-1; i++){ for(int j=0; j<n-1-i; j++){ if(a[j] > a[j+1]){ temp = a[j]; a[j] = a[j+1]; a[j+1] = temp; } } } } }
冒泡排序算法的改進:blog
對冒泡排序的改進是加入一標誌性變量exchange,用於標誌某一趟排序過程當中是否有數據交換,若是進行某一趟排序時,並無數據交換,則說明數據已經按要求排列好,可當即結束排序,避免沒必要要的比較過程,本文提供一下倆種改進算法:排序
一、設置一標誌性變量pos,用於記錄每一趟排序過程當中最後一交換數據的位置。因爲pos位置以後的數據已經按要求排列好了,因此下一趟排序的時候只須要掃描到pos位置便可。it
改進後算法以下:class
public class BubbleSort3 { public static void main(String[] args) { int[] a = { 12, 43, 65, 72, 87, 21, 98, 21, 911, 679, 22, 4, 1, 8, 2456, 32 }; bubbleSort(a, a.length); for (int i = 0; i < a.length; i++) { System.out.print(a[i] + " "); } } public static void bubbleSort(int[] a, int n) { int i = n - 1; // 初始時,最後位置保持不變 while (i > 0) { int pos = 0; // 每趟開始時,無記錄交換 for (int j = 0; j < i; j++) { if (a[j] > a[j + 1]) { pos = j; // 記錄交換的位置 int temp = a[j]; a[j] = a[j + 1]; a[j + 1] = temp; } } i = pos;// 爲下一趟排序做準備 } } }
二、傳統冒泡排序每一趟冒泡排序只能找到一個最大值或者最小值,咱們考慮利用在每趟排序中進行正向和反向倆遍的冒泡方法一次能夠獲得倆個值(最大值和最小值),從而使排序趟數幾乎減小一半。變量
改進後的算法爲:
public class BubbleSort4 { public static void main(String[] args) { int[] a = { 12, 43, 65, 72, 87, 21, 98, 21, 911, 679, 22, 4, 1, 8, 2456, 32 }; bubbleSort(a, a.length); for (int i = 0; i < a.length; i++) { System.out.print(a[i] + " "); } } public static void bubbleSort(int[] a, int n) { int low = 0; int high = n - 1; int temp, j; while (low < high) { for (j = low; j < high; ++j) { // 正向冒泡,找到最大值 if (a[j] > a[j + 1]) { temp = a[j]; a[j] = a[j + 1]; a[j + 1] = temp; } } --high;// 修改high值, 前移一位 for (j = high; j > low; --j) {// 反向冒泡,找到最小者 if (a[j] < a[j - 1]) { temp = a[j]; a[j] = a[j - 1]; a[j - 1] = temp; } } ++low;// 修改low值,後移一位 } } }