D.9 9장 연습문제 해설
- 연습문제 9.1.1 선형 탐색의 계산 비용
3은 첫째 원소와 같으므로 한 번 비교한다.9는 네 번째에서 만나므로3,7,2,9와 네 번 비교한다.4는 리스트에 없으므로 다섯 번 모두 비교한다. 입력 리스트의 길이는 세 경우 모두 같지만 탐색이 끝나는 위치에 따라 횟수가 달라진다.- 연습문제 9.1.2 두 알고리즘의 계산 비용 비교
입력 크기
5,10,20,100에서 비용의 순서쌍(T_A(n),T_B(n))은 각각(25,50),(100,100),(400,200),(10{,}000,1{,}000)이다.양의
n에서 두 비용을n으로 나누면n과10을 비교하면 된다. 따라서n=10에서 비용이 같고, 그보다 작을 때는A의 비용이, 그보다 클 때는B의 비용이 더 작다. 입력이 작을 때에는10이라는 상수 배수도 비교에 영향을 준다.
- 연습문제 9.2.1 리스트의 합 계산 비용
빈 리스트에서는
0을 반환하므로 덧셈이 없다. 머리x가 있으면 꼬리의 합을 구하고x를 한 번 더한다. 따라서 꼬리의 비용에1을 더한다. 아래 세 입력의 비용은 각각0,1,3이다.def listSumCost : List Nat → Nat | [] => 0 | _ :: xs => listSumCost xs + 1 #eval listSumCost [] #eval listSumCost [3] #eval listSumCost [3, 7, 2]- 연습문제 9.2.2 누산기를 사용하는 리스트 뒤집기의 비용
reverseAux는 각 머리 원소를 누산기 앞에 한 번 붙이므로 누산기에 이미 들어 있는 원소 수와 관계없이 단계마다1을 더한다.reverseSlowCost에는 이미 뒤집은 꼬리를 다시 구성하는 비용xs.length도 들어간다. 아래 순서쌍에서 첫째 성분은 연결 방식의 비용이고 둘째 성분은 누산기 방식의 비용이다. 결과는(0, 0),(1, 1),(10, 4)다.def reverseFastCost {α : Type} : List α → Nat | [] => 0 | _ :: xs => reverseFastCost xs + 1 #eval ([[], [1], [1, 2, 3, 4]] : List (List Nat)).map fun xs => (reverseSlowCost xs, reverseFastCost xs)- 연습문제 9.2.3 최댓값과 비교 횟수 함께 구하기
꼬리의 최댓값과 비용을 받아
x ≤ m을 검사한다. 어느 분기에서든 비교는 한 번이므로 비용에는1을 더한다. 원소의 순서가 바뀌면 어느 분기가 선택되는지는 달라질 수 있지만, 어느 경우에도 각 원소에서 비교를 한 번씩 하므로 비교 횟수는 리스트 길이와 같다.def listMaxWithCost : List Nat → Nat × Nat | [] => (0, 0) | x :: xs => let (m, cost) := listMaxWithCost xs (if x ≤ m then m else x, cost + 1) #eval listMaxWithCost [] #eval listMaxWithCost [3] #eval listMaxWithCost [3, 7, 2, 9, 5] #eval listMaxWithCost [5, 4, 3, 2, 1]- 연습문제 9.3.1 리스트의 합을 구하는 덧셈 횟수 증명하기
빈 리스트에서는 덧셈 횟수와 길이가 모두
0이다. 머리가 있는 분기에서listSumCost와List.length를 펼치면 양변이 꼬리에 관한 값에1을 더한 형태가 된다. 귀납 가정으로 그 두 값이 같음을 사용한다.theorem listSumCost_eq_length (xs : List Nat) : listSumCost xs = xs.length := xs:List Nat⊢ listSumCost xs = xs.length induction xs with ⊢ listSumCost [] = [].length All goals completed! 🐙 x:Natxs:List Natih:listSumCost xs = xs.length⊢ listSumCost (x :: xs) = (x :: xs).length All goals completed! 🐙- 연습문제 9.3.2 연결 방식의 뒤집기 비용 상한
0에서 비용은0이다.succ n분기에서 입력 크기는n + 1이다.Nat.mul_le_mul_left를 쓰면n + 1 + 1 ≤ (n + 1) + (n + 1)의 양쪽에 같은 자연수n + 1을 곱할 수 있다. 왼쪽을 비용의 두 배로 바꾸고 오른쪽을 전개하면 두 배에 관한 부등식이 된다. 마지막omega는 같은 곱(n + 1) * (n + 1)을 하나의 항으로 다룬다.theorem reverseCostBySize_le_square (n : Nat) : reverseCostBySize n ≤ n * n := n:Nat⊢ reverseCostBySize n ≤ n * n cases n with ⊢ reverseCostBySize 0 ≤ 0 * 0 All goals completed! 🐙 n:Nat⊢ reverseCostBySize (n + 1) ≤ (n + 1) * (n + 1)succ n:Nath:n + 1 + 1 ≤ n + 1 + (n + 1)⊢ reverseCostBySize (n + 1) ≤ (n + 1) * (n + 1)have hm := Nat.mul_le_mul_left (n + 1) h succ n:Nath:n + 1 + 1 ≤ n + 1 + (n + 1)hm:(n + 1) * (n + 1 + 1) ≤ (n + 1) * (n + 1 + (n + 1))⊢ reverseCostBySize (n + 1) ≤ (n + 1) * (n + 1)rw [ ← reverseCostBySize_formula (n + 1), succ n:Nath:n + 1 + 1 ≤ n + 1 + (n + 1)hm:2 * reverseCostBySize (n + 1) ≤ (n + 1) * (n + 1 + (n + 1))⊢ reverseCostBySize (n + 1) ≤ (n + 1) * (n + 1)Nat.mul_add succ n:Nath:n + 1 + 1 ≤ n + 1 + (n + 1)hm:2 * reverseCostBySize (n + 1) ≤ (n + 1) * (n + 1) + (n + 1) * (n + 1)⊢ reverseCostBySize (n + 1) ≤ (n + 1) * (n + 1)] at hmsucc n:Nath:n + 1 + 1 ≤ n + 1 + (n + 1)hm:2 * reverseCostBySize (n + 1) ≤ (n + 1) * (n + 1) + (n + 1) * (n + 1)⊢ reverseCostBySize (n + 1) ≤ (n + 1) * (n + 1)omega All goals completed! 🐙- 연습문제 9.3.3 탐색 대상이 없는 모든 리스트의 비용
h는 전체 리스트에 탐색 대상이 없다는 가정이다. 머리가 대상과 같다면List.mem_cons.mpr (Or.inl …)으로, 꼬리에 대상이 있다면List.mem_cons.mpr (Or.inr …)으로 포함 관계를 얻어h와 모순된다. 따라서 꼬리에서 탐색을 계속한다. 이때 대상이 없는 꼬리에 귀납 가정을 적용한다.theorem linearSearchCost_of_not_mem (target : Nat) (xs : List Nat) (h : target ∉ xs) : linearSearchCost target xs = xs.length :=by target:Natxs:List Nath:¬target ∈ xs⊢ linearSearchCost target xs = xs.length induction xs with| nil => nil target:Nath:¬target ∈ []⊢ linearSearchCost target [] = [].lengthrfl All goals completed! 🐙| cons x xs ih => cons target:Natx:Natxs:List Natih:¬target ∈ xs → linearSearchCost target xs = xs.lengthh:¬target ∈ x :: xs⊢ linearSearchCost target (x :: xs) = (x :: xs).lengthhave hhead : x ≠ target := by target:Natxs:List Nath:¬target ∈ xs⊢ linearSearchCost target xs = xs.lengthintro he target:Natx:Natxs:List Natih:¬target ∈ xs → linearSearchCost target xs = xs.lengthh:¬target ∈ x :: xshe:x = target⊢ False exact h (List.mem_cons.mpr (Or.inl he.symm))cons target:Natx:Natxs:List Natih:¬target ∈ xs → linearSearchCost target xs = xs.lengthh:¬target ∈ x :: xshhead:x ≠ target⊢ linearSearchCost target (x :: xs) = (x :: xs).lengthhave htail : target ∉ xs := by target:Natxs:List Nath:¬target ∈ xs⊢ linearSearchCost target xs = xs.lengthintro hm target:Natx:Natxs:List Natih:¬target ∈ xs → linearSearchCost target xs = xs.lengthh:¬target ∈ x :: xshhead:x ≠ targethm:target ∈ xs⊢ False exact h (List.mem_cons.mpr (Or.inr hm))cons target:Natx:Natxs:List Natih:¬target ∈ xs → linearSearchCost target xs = xs.lengthh:¬target ∈ x :: xshhead:x ≠ targethtail:¬target ∈ xs⊢ linearSearchCost target (x :: xs) = (x :: xs).lengthsimp [linearSearchCost, hhead, ih htail] All goals completed! 🐙- 연습문제 9.4.1 빅 오의 상수와 임계값 고르기
4n+6\le cn을6\le(c-4)n으로 바꾸어 각 쌍을 살핀다.(4,10)은n=10에서46>40이므로 성립하지 않는다.(5,5)는n=5에서26>25이다.(5,6)에서는n\ge6이면6\le n이어서 성립한다.(6,3)에서는n\ge3이면6\le 2n이고,(10,1)에서는n\ge1이면6\le 6n이다. 따라서 마지막 세 쌍을 증인으로 사용할 수 있다.- 연습문제 9.4.2 선형 비용 함수의 점근적 상한
c = 11,n₀ = 1을 택한다.n\ge1에서4\le4n이므로7n+4\le 11n이다.change로 람다식에n을 대입한 모양을 드러내면omega가 이 부등식을 처리한다.theorem exerciseLinear_bigO : BigO (fun n => 7 * n + 4) (fun n => n) :=by ⊢ BigO (fun n => 7 * n + 4) fun n => nunfold BigO ⊢ ∃ c, 0 < c ∧ ∃ n₀, ∀ (n : Nat), n₀ ≤ n → (fun n => 7 * n + 4) n ≤ c * (fun n => n) n refine ⟨11,by ⊢ 0 < 11decide All goals completed! 🐙, 1, ?_⟩intro n hn n:Nathn:1 ≤ n⊢ (fun n => 7 * n + 4) n ≤ 11 * (fun n => n) nchange 7 * n + 4 ≤ 11 * n n:Nathn:1 ≤ n⊢ 7 * n + 4 ≤ 11 * nomega All goals completed! 🐙선택 실습의 상한은
linearCost_bigO에서 얻는다. 하한을 보일 때는BigO의 인수 순서를 바꾼 목표BigO (fun n => n) (fun n => 3 * n + 2)에서c = 1,n₀ = 0을 택한다.example : BigTheta (fun n => 3 * n + 2) (fun n => n) :=by ⊢ BigTheta (fun n => 3 * n + 2) fun n => nrefine ⟨linearCost_bigO, ?_⟩ ⊢ BigOmega (fun n => 3 * n + 2) fun n => nunfold BigOmega BigO ⊢ ∃ c, 0 < c ∧ ∃ n₀, ∀ (n : Nat), n₀ ≤ n → (fun n => n) n ≤ c * (fun n => 3 * n + 2) n refine ⟨1,by ⊢ 0 < 1decide All goals completed! 🐙, 0, ?_⟩intro n _ n:Nata✝:0 ≤ n⊢ (fun n => n) n ≤ 1 * (fun n => 3 * n + 2) nchange n ≤ 1 * (3 * n + 2) n:Nata✝:0 ≤ n⊢ n ≤ 1 * (3 * n + 2)omega All goals completed! 🐙- 연습문제 9.4.3 이차 비용 함수의 점근적 상한
n\ge1이면5n\le5n^2이고3\le3n^2이다. 이 두 상한을 기존의n^2에 더하면n^2+5n+3\le9n^2을 얻는다. 따라서c = 9,n₀ = 1을 쓴다.theorem exerciseQuadratic_bigO : BigO (fun n => n * n + 5 * n + 3) (fun n => n * n) :=by ⊢ BigO (fun n => n * n + 5 * n + 3) fun n => n * nunfold BigO ⊢ ∃ c, 0 < c ∧ ∃ n₀, ∀ (n : Nat), n₀ ≤ n → (fun n => n * n + 5 * n + 3) n ≤ c * (fun n => n * n) n refine ⟨9,by ⊢ 0 < 9decide All goals completed! 🐙, 1, ?_⟩intro n hn n:Nathn:1 ≤ n⊢ (fun n => n * n + 5 * n + 3) n ≤ 9 * (fun n => n * n) nchange n * n + 5 * n + 3 ≤ 9 * (n * n) n:Nathn:1 ≤ n⊢ n * n + 5 * n + 3 ≤ 9 * (n * n)have h : n ≤ n * n := n:Nathn:1 ≤ nh:n ≤ n * n⊢ n * n + 5 * n + 3 ≤ 9 * (n * n)by ⊢ BigO (fun n => n * n + 5 * n + 3) fun n => n * n simpa only [Nat.mul_one] using Nat.mul_le_mul_left n hnhave h₁ : 1 ≤ n * n := Nat.le_trans hn h n:Nathn:1 ≤ nh:n ≤ n * nh₁:1 ≤ n * n⊢ n * n + 5 * n + 3 ≤ 9 * (n * n)omega All goals completed! 🐙- 연습문제 9.5.1 증가율이 같은 두 비용 함수 비교하기
길이가
1이상일 때3 ≤ 3 * n,1 ≤ n이므로 상한에costA는8 * n,costB는3 * n을 쓸 수 있다. 하한은 둘 다 모든 자연수에서n이다. 코드에서는BigOmega를 펼친 뒤c = 1,n₀ = 0으로 하한을 보인다.theorem costA_bigTheta : BigTheta costA (fun n => n) :=by ⊢ BigTheta costA fun n => nconstructor left ⊢ BigO costA fun n => nright ⊢ BigOmega costA fun n => n· left ⊢ BigO costA fun n => nunfold BigO left ⊢ ∃ c, 0 < c ∧ ∃ n₀, ∀ (n : Nat), n₀ ≤ n → costA n ≤ c * (fun n => n) n refine ⟨8,by ⊢ 0 < 8decide All goals completed! 🐙, 1, ?_⟩intro n hn left n:Nathn:1 ≤ n⊢ costA n ≤ 8 * (fun n => n) nchange costA n ≤ 8 * n left n:Nathn:1 ≤ n⊢ costA n ≤ 8 * nunfold costA left n:Nathn:1 ≤ n⊢ 5 * n + 3 ≤ 8 * nomega All goals completed! 🐙· right ⊢ BigOmega costA fun n => nunfold BigOmega BigO right ⊢ ∃ c, 0 < c ∧ ∃ n₀, ∀ (n : Nat), n₀ ≤ n → (fun n => n) n ≤ c * costA n refine ⟨1,by ⊢ 0 < 1decide All goals completed! 🐙, 0, ?_⟩intro n _ right n:Nata✝:0 ≤ n⊢ (fun n => n) n ≤ 1 * costA nchange n ≤ 1 * costA n right n:Nata✝:0 ≤ n⊢ n ≤ 1 * costA nunfold costA right n:Nata✝:0 ≤ n⊢ n ≤ 1 * (5 * n + 3)omega All goals completed! 🐙 theorem costB_bigTheta : BigTheta costB (fun n => n) :=by ⊢ BigTheta costB fun n => nconstructor left ⊢ BigO costB fun n => nright ⊢ BigOmega costB fun n => n· left ⊢ BigO costB fun n => nunfold BigO left ⊢ ∃ c, 0 < c ∧ ∃ n₀, ∀ (n : Nat), n₀ ≤ n → costB n ≤ c * (fun n => n) n refine ⟨3,by ⊢ 0 < 3decide All goals completed! 🐙, 1, ?_⟩intro n hn left n:Nathn:1 ≤ n⊢ costB n ≤ 3 * (fun n => n) nchange costB n ≤ 3 * n left n:Nathn:1 ≤ n⊢ costB n ≤ 3 * nunfold costB left n:Nathn:1 ≤ n⊢ 2 * n + 1 ≤ 3 * nomega All goals completed! 🐙· right ⊢ BigOmega costB fun n => nunfold BigOmega BigO right ⊢ ∃ c, 0 < c ∧ ∃ n₀, ∀ (n : Nat), n₀ ≤ n → (fun n => n) n ≤ c * costB n refine ⟨1,by ⊢ 0 < 1decide All goals completed! 🐙, 0, ?_⟩intro n _ right n:Nata✝:0 ≤ n⊢ (fun n => n) n ≤ 1 * costB nchange n ≤ 1 * costB n right n:Nata✝:0 ≤ n⊢ n ≤ 1 * costB nunfold costB right n:Nata✝:0 ≤ n⊢ n ≤ 1 * (2 * n + 1)omega All goals completed! 🐙두 함수의 차는 수학적으로
(5n+3)-(2n+1)=3n+2이고 모든 자연수에서 양수다. 두 함수에는 같은 선형 차수를 부여할 수 있으며, 어느 입력에서든costB의 정확한 비용이 더 작다.- 연습문제 9.5.2 길이가 2 이상일 때 뒤집기 비용의 엄격한 감소
길이가
0인 분기는 가정2 ≤ n과 모순된다. 길이가n + 1이면reverseCost_improved n으로 길이n에서 누산기 방식의 비용이 더 크지 않음을 얻는다. 이제 누산기 방식에는1을, 연결 방식에는n + 1을 더한다. 가정에 의해n + 1이1보다 커서 새 비용에는 엄격한 부등식이 성립한다. 길이0과1에서는 양변이 각각0과1로 계산된다.theorem reverseCost_strictly_improved (n : Nat) (h : 2 ≤ n) : reverseFastCostBySize n < reverseCostBySize n :=by n:Nath:2 ≤ n⊢ reverseFastCostBySize n < reverseCostBySize n cases n with| zero => zero h:2 ≤ 0⊢ reverseFastCostBySize 0 < reverseCostBySize 0omega All goals completed! 🐙| succ n => succ n:Nath:2 ≤ n + 1⊢ reverseFastCostBySize (n + 1) < reverseCostBySize (n + 1)have ih := reverseCost_improved n succ n:Nath:2 ≤ n + 1ih:reverseFastCostBySize n ≤ reverseCostBySize n⊢ reverseFastCostBySize (n + 1) < reverseCostBySize (n + 1)simp only [reverseFastCostBySize, reverseCostBySize] at ih ⊢ succ n:Nath:2 ≤ n + 1ih:n ≤ reverseCostBySize n⊢ n + 1 < reverseCostBySize n + (n + 1)omega All goals completed! 🐙 example : reverseFastCostBySize 0 = reverseCostBySize 0 := rfl example : reverseFastCostBySize 1 = reverseCostBySize 1 := rfl- 연습문제 9.6.1 삽입 연산의 최소 비용
첫 비교의 조건이 참이면 그 비교 한 번으로 삽입할 위치가 정해진다. 조건이 거짓이어도 첫 비교는 이미 했으므로 꼬리에서 비교한 횟수에
1을 더한다. 따라서 빈 리스트가 아니면 적어도 한 번은 비교한다.theorem insertCost_first (x y : Nat) (ys : List Nat) (h : x ≤ y) : insertCost x (y :: ys) = 1 :=by x:Naty:Natys:List Nath:x ≤ y⊢ insertCost x (y :: ys) = 1simp [insertCost, h] All goals completed! 🐙 theorem insertCost_ge_one (x y : Nat) (ys : List Nat) : 1 ≤ insertCost x (y :: ys) :=by x:Naty:Natys:List Nat⊢ 1 ≤ insertCost x (y :: ys)by_cases h : x ≤ y pos x:Naty:Natys:List Nath:x ≤ y⊢ 1 ≤ insertCost x (y :: ys)neg x:Naty:Natys:List Nath:¬x ≤ y⊢ 1 ≤ insertCost x (y :: ys)<;> pos x:Naty:Natys:List Nath:x ≤ y⊢ 1 ≤ insertCost x (y :: ys)neg x:Naty:Natys:List Nath:¬x ≤ y⊢ 1 ≤ insertCost x (y :: ys)simp [insertCost, h] All goals completed! 🐙- 연습문제 9.6.2 계산 결과와 계산 비용의 일치
먼저 삽입 결과와 비용의 등식을 한 순서쌍의 등식으로 증명한다. 빈 리스트에서는 세 함수의 정의가 바로 줄어든다. 비어 있지 않으면
x ≤ y로 분기하고, 삽입을 계속하는 분기에서는 꼬리에 대한 귀납 가정으로 재귀 호출의 순서쌍을 바꾼다. 각 성분의 정리는 이 등식을 왼쪽에 적용해 얻는다.theorem insertWithCost_eq (x : Nat) (xs : List Nat) : insertWithCost x xs = (insertNat x xs, insertCost x xs) :=by x:Natxs:List Nat⊢ insertWithCost x xs = (insertNat x xs, insertCost x xs) induction xs with| nil => nil x:Nat⊢ insertWithCost x [] = (insertNat x [], insertCost x [])rfl All goals completed! 🐙| cons y ys ih => cons x:Naty:Natys:List Natih:insertWithCost x ys = (insertNat x ys, insertCost x ys)⊢ insertWithCost x (y :: ys) = (insertNat x (y :: ys), insertCost x (y :: ys))by_cases h : x ≤ y pos x:Naty:Natys:List Natih:insertWithCost x ys = (insertNat x ys, insertCost x ys)h:x ≤ y⊢ insertWithCost x (y :: ys) = (insertNat x (y :: ys), insertCost x (y :: ys))neg x:Naty:Natys:List Natih:insertWithCost x ys = (insertNat x ys, insertCost x ys)h:¬x ≤ y⊢ insertWithCost x (y :: ys) = (insertNat x (y :: ys), insertCost x (y :: ys))· pos x:Naty:Natys:List Natih:insertWithCost x ys = (insertNat x ys, insertCost x ys)h:x ≤ y⊢ insertWithCost x (y :: ys) = (insertNat x (y :: ys), insertCost x (y :: ys))simp [insertWithCost, insertNat, insertCost, h] All goals completed! 🐙· neg x:Naty:Natys:List Natih:insertWithCost x ys = (insertNat x ys, insertCost x ys)h:¬x ≤ y⊢ insertWithCost x (y :: ys) = (insertNat x (y :: ys), insertCost x (y :: ys))simp [insertWithCost, insertNat, insertCost, h, ih] All goals completed! 🐙 theorem insertWithCost_result (x : Nat) (xs : List Nat) : (insertWithCost x xs).1 = insertNat x xs :=by x:Natxs:List Nat⊢ (insertWithCost x xs).fst = insertNat x xsrw [ All goals completed! 🐙 theorem insertWithCost_cost (x : Nat) (xs : List Nat) : (insertWithCost x xs).2 = insertCost x xs :=insertWithCost_eq x:Natxs:List Nat⊢ (insertNat x xs, insertCost x xs).fst = insertNat x xs]by x:Natxs:List Nat⊢ (insertWithCost x xs).snd = insertCost x xsrw [ All goals completed! 🐙insertWithCost_eq x:Natxs:List Nat⊢ (insertNat x xs, insertCost x xs).snd = insertCost x xs]전체 정렬의 귀납 단계에서는 귀납 가정으로 꼬리 정렬의 결과와 비용을 얻는다. 그 정렬 결과에
insertWithCost_eq를 적용하면 현재 삽입의 결과와 비용도 얻는다. 두 비용을 더한 식은insertionSortCost의 귀납 분기와 같다.theorem insertionSortWithCost_eq (xs : List Nat) : insertionSortWithCost xs = (insertionSort xs, insertionSortCost xs) :=by xs:List Nat⊢ insertionSortWithCost xs = (insertionSort xs, insertionSortCost xs) induction xs with| nil => nil ⊢ insertionSortWithCost [] = (insertionSort [], insertionSortCost [])rfl All goals completed! 🐙| cons x xs ih => cons x:Natxs:List Natih:insertionSortWithCost xs = (insertionSort xs, insertionSortCost xs)⊢ insertionSortWithCost (x :: xs) = (insertionSort (x :: xs), insertionSortCost (x :: xs))simp [insertionSortWithCost, ih, insertWithCost_eq, insertionSort, insertionSortCost] All goals completed! 🐙 theorem insertionSortWithCost_result (xs : List Nat) : (insertionSortWithCost xs).1 = insertionSort xs :=by xs:List Nat⊢ (insertionSortWithCost xs).fst = insertionSort xsrw [ All goals completed! 🐙 theorem insertionSortWithCost_cost (xs : List Nat) : (insertionSortWithCost xs).2 = insertionSortCost xs :=insertionSortWithCost_eq xs:List Nat⊢ (insertionSort xs, insertionSortCost xs).fst = insertionSort xs]by xs:List Nat⊢ (insertionSortWithCost xs).snd = insertionSortCost xsrw [ All goals completed! 🐙insertionSortWithCost_eq xs:List Nat⊢ (insertionSort xs, insertionSortCost xs).snd = insertionSortCost xs]- 연습문제 9.6.3 삽입 정렬의 최선의 경우 복잡도
1. 길이별 비교 횟수. 빈 리스트와 원소가 하나인 리스트에서는 비교할 원소가 없으므로 비용이
0이다. 0이 네 개면 첫 원소를 제외한 각 삽입에 비교가 한 번씩 필요해 비용이3이다.#eval [0, 1, 4].map (fun n => insertionSortCost (List.replicate n 0))2. 하한에 도달하는 입력.
0만 있는 리스트는 정렬을 거쳐도 같다. 꼬리가 비어 있으면 비교 없이[0]을 만들고, 꼬리가 비어 있지 않으면 첫 비교0 ≤ 0이 참이므로 그 앞에0을 놓는다. 따라서 길이가n + 1이면 꼬리 길이가0인 경우 비용은0이고, 그 외에는 꼬리의 비용에1을 더해n이 된다.theorem insertionSort_replicate_zero (n : Nat) : insertionSort (List.replicate n 0) = List.replicate n 0 :=by n:Nat⊢ insertionSort (List.replicate n 0) = List.replicate n 0 induction n with| zero => zero ⊢ insertionSort (List.replicate 0 0) = List.replicate 0 0rfl All goals completed! 🐙| succ n ih => succ n:Natih:insertionSort (List.replicate n 0) = List.replicate n 0⊢ insertionSort (List.replicate (n + 1) 0) = List.replicate (n + 1) 0rw [ List.replicate_succ, succ n:Natih:insertionSort (List.replicate n 0) = List.replicate n 0⊢ insertionSort (0 :: List.replicate n 0) = 0 :: List.replicate n 0insertionSort, succ n:Natih:insertionSort (List.replicate n 0) = List.replicate n 0⊢ insertNat 0 (insertionSort (List.replicate n 0)) = 0 :: List.replicate n 0ih succ n:Natih:insertionSort (List.replicate n 0) = List.replicate n 0⊢ insertNat 0 (List.replicate n 0) = 0 :: List.replicate n 0]succ n:Natih:insertionSort (List.replicate n 0) = List.replicate n 0⊢ insertNat 0 (List.replicate n 0) = 0 :: List.replicate n 0 cases n with| zero => succ.zero ih:insertionSort (List.replicate 0 0) = List.replicate 0 0⊢ insertNat 0 (List.replicate 0 0) = 0 :: List.replicate 0 0rfl All goals completed! 🐙| succ n => succ.succ n:Natih:insertionSort (List.replicate (n + 1) 0) = List.replicate (n + 1) 0⊢ insertNat 0 (List.replicate (n + 1) 0) = 0 :: List.replicate (n + 1) 0simp [List.replicate_succ, insertNat] All goals completed! 🐙 theorem insertionSortCost_replicate (n : Nat) : insertionSortCost (List.replicate n 0) = n - 1 :=by n:Nat⊢ insertionSortCost (List.replicate n 0) = n - 1 induction n with| zero => zero ⊢ insertionSortCost (List.replicate 0 0) = 0 - 1rfl All goals completed! 🐙| succ n ih => succ n:Natih:insertionSortCost (List.replicate n 0) = n - 1⊢ insertionSortCost (List.replicate (n + 1) 0) = n + 1 - 1rw [ List.replicate_succ, succ n:Natih:insertionSortCost (List.replicate n 0) = n - 1⊢ insertionSortCost (0 :: List.replicate n 0) = n + 1 - 1insertionSortCost, succ n:Natih:insertionSortCost (List.replicate n 0) = n - 1⊢ insertionSortCost (List.replicate n 0) + insertCost 0 (insertionSort (List.replicate n 0)) = n + 1 - 1ih, succ n:Natih:insertionSortCost (List.replicate n 0) = n - 1⊢ n - 1 + insertCost 0 (insertionSort (List.replicate n 0)) = n + 1 - 1insertionSort_replicate_zero succ n:Natih:insertionSortCost (List.replicate n 0) = n - 1⊢ n - 1 + insertCost 0 (List.replicate n 0) = n + 1 - 1]succ n:Natih:insertionSortCost (List.replicate n 0) = n - 1⊢ n - 1 + insertCost 0 (List.replicate n 0) = n + 1 - 1 cases n with| zero => succ.zero ih:insertionSortCost (List.replicate 0 0) = 0 - 1⊢ 0 - 1 + insertCost 0 (List.replicate 0 0) = 0 + 1 - 1rfl All goals completed! 🐙| succ n => succ.succ n:Natih:insertionSortCost (List.replicate (n + 1) 0) = n + 1 - 1⊢ n + 1 - 1 + insertCost 0 (List.replicate (n + 1) 0) = n + 1 + 1 - 1simp [List.replicate_succ, insertCost] All goals completed! 🐙3. 모든 입력의 하한. 임의의 입력에서도 원소가 둘 이상이면 정렬한 꼬리가 비어 있지 않다. 이를
insertionSort_length로 확인하고insertCost_ge_one을 적용한다. 꼬리의 귀납 가정에 삽입의 하한1을 더하면 전체 비용은 적어도xs.length - 1이다.theorem insertionSortCost_lower_bound (xs : List Nat) : xs.length - 1 ≤ insertionSortCost xs :=by xs:List Nat⊢ xs.length - 1 ≤ insertionSortCost xs induction xs with| nil => nil ⊢ [].length - 1 ≤ insertionSortCost []exact Nat.le_refl 0 All goals completed! 🐙| cons x xs ih => cons x:Natxs:List Natih:xs.length - 1 ≤ insertionSortCost xs⊢ (x :: xs).length - 1 ≤ insertionSortCost (x :: xs) cases xs with| nil => cons.nil x:Natih:[].length - 1 ≤ insertionSortCost []⊢ [x].length - 1 ≤ insertionSortCost [x]exact Nat.le_refl 0 All goals completed! 🐙| cons y ys => cons.cons x:Naty:Natys:List Natih:(y :: ys).length - 1 ≤ insertionSortCost (y :: ys)⊢ (x :: y :: ys).length - 1 ≤ insertionSortCost (x :: y :: ys)have hlen := insertionSort_length (y :: ys) cons.cons x:Naty:Natys:List Natih:(y :: ys).length - 1 ≤ insertionSortCost (y :: ys)hlen:(insertionSort (y :: ys)).length = (y :: ys).length⊢ (x :: y :: ys).length - 1 ≤ insertionSortCost (x :: y :: ys)have hi : 1 ≤ insertCost x (insertionSort (y :: ys)) := by xs:List Nat⊢ xs.length - 1 ≤ insertionSortCost xs cases h : insertionSort (y :: ys) with| nil => nil x:Naty:Natys:List Natih:(y :: ys).length - 1 ≤ insertionSortCost (y :: ys)hlen:(insertionSort (y :: ys)).length = (y :: ys).lengthh:insertionSort (y :: ys) = []⊢ 1 ≤ insertCost x []simp [h] at hlen All goals completed! 🐙| cons z zs => cons x:Naty:Natys:List Natih:(y :: ys).length - 1 ≤ insertionSortCost (y :: ys)hlen:(insertionSort (y :: ys)).length = (y :: ys).lengthz:Natzs:List Nath:insertionSort (y :: ys) = z :: zs⊢ 1 ≤ insertCost x (z :: zs) exact insertCost_ge_one x z zscons.cons x:Naty:Natys:List Natih:(y :: ys).length - 1 ≤ insertionSortCost (y :: ys)hlen:(insertionSort (y :: ys)).length = (y :: ys).lengthhi:1 ≤ insertCost x (insertionSort (y :: ys))⊢ (x :: y :: ys).length - 1 ≤ insertionSortCost (x :: y :: ys)rw [ insertionSortCost, cons.cons x:Naty:Natys:List Natih:(y :: ys).length - 1 ≤ insertionSortCost (y :: ys)hlen:(insertionSort (y :: ys)).length = (y :: ys).lengthhi:1 ≤ insertCost x (insertionSort (y :: ys))⊢ (x :: y :: ys).length - 1 ≤ insertionSortCost (y :: ys) + insertCost x (insertionSort (y :: ys))List.length_cons cons.cons x:Naty:Natys:List Natih:(y :: ys).length - 1 ≤ insertionSortCost (y :: ys)hlen:(insertionSort (y :: ys)).length = (y :: ys).lengthhi:1 ≤ insertCost x (insertionSort (y :: ys))⊢ (y :: ys).length + 1 - 1 ≤ insertionSortCost (y :: ys) + insertCost x (insertionSort (y :: ys))]cons.cons x:Naty:Natys:List Natih:(y :: ys).length - 1 ≤ insertionSortCost (y :: ys)hlen:(insertionSort (y :: ys)).length = (y :: ys).lengthhi:1 ≤ insertCost x (insertionSort (y :: ys))⊢ (y :: ys).length + 1 - 1 ≤ insertionSortCost (y :: ys) + insertCost x (insertionSort (y :: ys))omega All goals completed! 🐙4. 최선 비용의 증가율. 두 번째 단계의 등식은 한 입력의 비용을 확정한다. 세 번째 단계의 부등식은 같은 길이의 모든 입력에서 그 비용이 하한임을 보장한다. 두 결과를 합치면 최선 비용은
n - 1이다. 모든 자연수에서n - 1 ≤ n이고,n ≥ 2이면n ≤ 2 * (n - 1)이다. 각각의 비교로 빅 오와 빅 오메가를 증명한다.def insertionSortBestCost (n : Nat) : Nat := n - 1 theorem insertionSort_best_bigTheta : BigTheta insertionSortBestCost (fun n => n) :=by ⊢ BigTheta insertionSortBestCost fun n => nconstructor left ⊢ BigO insertionSortBestCost fun n => nright ⊢ BigOmega insertionSortBestCost fun n => n· left ⊢ BigO insertionSortBestCost fun n => nunfold BigO left ⊢ ∃ c, 0 < c ∧ ∃ n₀, ∀ (n : Nat), n₀ ≤ n → insertionSortBestCost n ≤ c * (fun n => n) n refine ⟨1,by ⊢ 0 < 1decide All goals completed! 🐙, 0, ?_⟩intro n _ left n:Nata✝:0 ≤ n⊢ insertionSortBestCost n ≤ 1 * (fun n => n) nchange n - 1 ≤ 1 * n left n:Nata✝:0 ≤ n⊢ n - 1 ≤ 1 * nomega All goals completed! 🐙· right ⊢ BigOmega insertionSortBestCost fun n => nunfold BigOmega BigO right ⊢ ∃ c, 0 < c ∧ ∃ n₀, ∀ (n : Nat), n₀ ≤ n → (fun n => n) n ≤ c * insertionSortBestCost n refine ⟨2,by ⊢ 0 < 2decide All goals completed! 🐙, 2, ?_⟩intro n hn right n:Nathn:2 ≤ n⊢ (fun n => n) n ≤ 2 * insertionSortBestCost nchange n ≤ 2 * (n - 1) right n:Nathn:2 ≤ n⊢ n ≤ 2 * (n - 1)omega All goals completed! 🐙