Java與算法之(9) - 直接插入排序
來源:程序員人生 發布時間:2016-11-10 08:31:01 閱讀次數:2436次
直接插入排序是最簡單的排序算法,也比較符合人的思惟習慣。想像1下玩撲克牌抓牌的進程。第1張抓到5,放在手里;第2張抓到3,習慣性的會把它放在5的前面;第3張抓到7,放在5的后面;第4張抓到4,那末我們會把它放在3和5的中間。

直接插入排序正是這類思路,每次取1個數,從前向后找,找到適合的位置就插進去。
代碼也非常簡單:
/**
* 直接插入排序法
* Created by autfish on 2016/9/18.
*/
public class InsertSort {
private int[] numbers;
public InsertSort(int[] numbers) {
this.numbers = numbers;
}
public void sort() {
int temp;
for(int i = 1; i < this.numbers.length; i++) {
temp = this.numbers[i]; //取出1個未排序的數
for(int j = i - 1; j >= 0 && temp < this.numbers[j]; j--) {
this.numbers[j + 1] = this.numbers[j];
this.numbers[j] = temp;
}
}
System.out.print("排序后: ");
for(int x = 0; x < numbers.length; x++) {
System.out.print(numbers[x] + " ");
}
}
public static void main(String[] args) {
int[] numbers = new int[] { 4, 3, 6, 2, 7, 1, 5 };
System.out.print("排序前: ");
for(int x = 0; x < numbers.length; x++) {
System.out.print(numbers[x] + " ");
}
System.out.println();
InsertSort is = new InsertSort(numbers);
is.sort();
}
}
測試結果:
排序前: 4 3 6 2 7 1 5
排序后: 1 2 3 4 5 6 7
直接插入排序的時間復雜度,最好情況是O(n),最壞是O(n^2),平均O(n^2)。
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈