Try   HackMD

資料結構與演算法—插入排序 Insertion Sort

筆記頁面:資料結構與演算法

Pseudo Code

INSERTION-SORT(A,n)
1for i = 2 to n
2    key= A [i]
3    // Insert A[i] into the sorted subarray A[1:i-1]
4    j = i - 1
5    while j > 0 and A[j] > key
6        A[j + 1] = A[j]
7        j = j - 1
8    A[j + 1] = key

時間複雜度分析

line cost times
1
c1
n
2
c2
n1
3
c3
n1
4
c4
n1
5
c5
i=2nti
6
c6
i=2n(ti1)
7
c7
i=2n(ti1)
8
c8
n1

T(n)=c1n+c2(n1)+c3(n1)+c4(n1)+c5i=2nti+c6i=2n(ti1)+c7i=2n(ti1)+c8(n1)

Best Case

the best case occurs when the array is already sorted
line 5-7 will never be executed

T(n)=(c1+c2+c3+c4+c8)n(c2+c3+c4+c8)let a=c1+c2+c3+c4+c8let b=c2+c3+c4+c8T(n)=anb

最佳情況所消耗之時間為線性增長的

O(n)

Worst Case

最糟情況是每一次的排序,都要把要插入的值移到第一個位置。也就是說 5-7 行都會跑滿,使得

ti=i。因此我們可以將 Summation 的式子化簡:

i=2nti=i=2ni=(i=1ni)1=n(n+1)21i=2n(ti1)=i=2n(i1)=i=1n1i=(n1)(n1+1)2=n(n1)2

在將化簡後的式子帶入原式:

T(n)=c1n+c2(n1)+c3(n1)+c4(n1)+c5(n(n+1)21)+c6(n(n1)2)+c7(n(n1)2)+c8(n1)=(c52+c62+c72)n2+(c1+c2+c3+c4+c52c62c72+c8)n(c2+c4+c5+c8)let a=c52+c62+c72let b=c1+c2+c3+c4+c52c62c72+c8let c=c2+c4+c5+c8T(n)=an2+bnc

最糟情況所消耗之時間為指數增長的

O(n2)

C Code

void Insert_Sort(int *arr, int len) {
    
    // i is point to value to insert
	for(int i = 1; i < len; i++) {
		int item = arr[i];
		
		// shift back when sorted value is large than item
		int j = i - 1;
		for(; j >= 0 && arr[j] > item; j--) {
			arr[j+1] = arr[j];
		}
        
		// insert into empty position
		arr[j+1] = item;
	}
}