排序算法是一種基本、常用的算法。排序算法分爲內部排序和外部排序。
內部排序是指整個排序過程不需要訪問外存就能完成。
外部排序是指黨對大批量數據進行排序時,不可能一次性將全部數據裝入內存,只能從外存讀取一部分數據到內存中,將內存中的數據進行排序後,再存儲到外存中,然後再從外存中讀取下一部分數據到內存中,最後,對已經排序的子部分進行歸併排序。
冒泡排序是一種相鄰數據交換的排序方法。冒泡排序的特點是對於n個元素要進行n-1次掃描,那麼有時候可能掃描一兩次數據就已經排好序了,後面再掃描明顯就是浪費計算資源了,所以可以對冒泡排序進行一些改進,代碼如下:
public class BubbleSort {
public void bubbleSort(int[] in) {
boolean isBubble = false;
int inLength = in.length;
for (int i = 0; i < inLength; i++) {
System.out.print("第" + i + "遍: ");
for (int k : in) {
System.out.print(k + " ");
}
System.out.println();
for (int j = inLength - 1; j > i; j--) {
if (in[j] < in[j - 1]) {
isBubble = true;
int tmp = in[j];
in[j] = in[j - 1];
in[j - 1] = tmp;
}
}
if (!isBubble) {
break;
} else {
isBubble = false;
}
}
}
public static void main(String[] args) {
BubbleSort mBubbleSort = new BubbleSort();
int[] caseOne = { 6, 5, 4, 3, 2, 1, 10, 2 };
int[] caseTwo = { 1, 6, 5, 2, 4, 3 };
mBubbleSort.bubbleSort(caseOne);
for (int i : caseOne) {
System.out.print(i + " ");
}
System.out.println();
mBubbleSort.bubbleSort(caseTwo);
for (int i : caseTwo) {
System.out.print(i + " ");
}
}
}