《演算法導論》2 2練習答案

2021-10-16 12:52:31 字數 1019 閱讀 7157

捨棄它的低階項,並忽略前面的常數因子

θ(n3)

2.2-2考慮排序儲存在陣列a中的n個數:首先找出a中的最小元素並將其與a[1]中的元素進行交換。接著,找出a中的次最小元素並將其與a[2]中的元素進行交換。對a中前n - 1個元素按該方式繼續。該演算法稱為選擇演算法,寫出其偽**。該演算法維持的迴圈不變式是什麼?為什麼它只需要對前n-1個元素執行?用θ記號給出選擇排序的最好情況和最壞情況執行時間。

(1)偽**:

selection-sort(a)

for i=1 to a.length-1

min_loc=i

for j=i+1 to a.length

if a[j]附贈c語言實現:

//用c語言實現選擇排序

#include

#define swap(x,y) x=x+y;y=x-y;x=x-y

void

selectsort

(int

* a,

int n)}if

(min_loc != i)}}

main()

;selectsort

(a,8);

for(

int i =

0; i <

8; i++

)printf

("%d "

, a[i]);

//輸出:1 2 2 3 4 5 6 7

}

(2)迴圈不變式:在(變數為i的)for迴圈每次迭代開始時,子串行a[1…i]包含已排序好的最小的i個元素。

(3)因為在n-1次(變數為i的)迴圈後,子串行a[1…n-1]包含a中已排好序的前n-1個最小元素,因此這時a[n]一定已經是最大的了。

(4)θ(n2)

平均要檢查n/2個,θ(n)

最壞情況要檢查n個,θ(n)

可以針對特定條件的問題做針對性的樣例,如果遇到這種(可能是出現概率較高的)特定條件直接輸出準備好的結果,這是針對特定問題的優化。

演算法導論 練習2 2

2.2 1 只看最高次項,並忽略係數,時間複雜度為 n 3 2.2 2 def swap a,b return b,a defselect sort a n len a for i in range n 1 minindex i for j in range i 1 n if a j mininde...

《演算法導論》2 1練習答案

2.1 1應該不用寫了 2.1 2重寫過程inertion sort,使之按公升序排序 偽 實現 inertion sort a for j 2 to a.length key a j insert a j to the sorted sequence a 1.j 1 i j 1 while i 0...

演算法導論2 3練習答案

使用哨兵的歸併排序 merge sort 見文章 c語言實現歸併排序 無哨兵版 include include include include void merge int a,int p,int q,int r r中的元素複製完畢,只需繼續複製l中的 else if j n2 從l r陣列中取更小...