1.1 冒泡排序原理
舉個例子
利用冒泡排序對下面 n 個元素按照從大到小的順序進行排序: (1,5,3,9,12,7,15,10)
動畫演示
對於例中的 n 個元素的排序過程如下:
Tip: 相鄰元素比較次數爲 n-1 次
Java語言實現
public class Sort {
public static void bubbleSort(int[] arr) {
for(int i = 0; i < arr.length; i++) {
boolean flag = false;
for(int j = 0; j < arr.length-1; j++) {
if(arr[j] < arr[j+1]) {
int t = arr[j];
arr[j] = arr[j+1];
arr[j+1] = t;
flag = true;
}
}
if(flag == false){
break;
}
}
}
}
Tip: 這裏使用 flag 來處理已經排序好的情況
測試結果
public class Test {
public static void main(String[] args) {
int[] arr = new int[]{1,5,3,9,12,7,15,10};
Sort.bubbleSort(arr);
for(int a: arr) {
System.out.println(a);
}
}
}/*output:
[15, 12, 10, 9, 7, 5, 3, 1]
*/
時間複雜度分析
最好的情況下:元素已經按照大小順序排序,只需要比較 n-1 次,時間複雜度爲 O(n)
最壞的情況下:元素按照倒序排序,需要執行 n (n - 1) 次比較,時間複雜度爲O( n2 )
1.2 選擇排序原理
在未排序的序列中找到最大(最小值)依次有序放入排序好的序列中。
舉個例子
利用選擇排序對下面 n 個元素按照從大到小的順序進行排序: (1, 5, 3, 9, 12, 7, 15, 10)
動畫演示
Java語言實現
public class Sort {
public static void selectSort(int[] arr) {
int maxId;
for(int i = 0; i < arr.length; i++) {
maxId = i;
for(int j = i+1; j < arr.length; j++) {
if(arr[j] > arr[maxId]) {
maxId = j;
}
}
int t = arr[i];
arr[i] = arr[maxId];
arr[maxId] = t;
}
}
}
測試結果
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
int[] arr = new int[] {1, 5, 3, 9, 12, 7, 15, 10};
Sort.selectSort(arr);
System.out.println(Arrays.toString(arr));
}
}/*output:
[15, 12, 10, 9, 7, 5, 3, 1]
*/
時間複雜度分析
選擇排序無論是哪個元素進去,都要進行兩次循環操作,所以時間複雜度爲 O(n2)